﻿// Decompiled with JetBrains decompiler
// Type: MT5Trade.MtTrade5
// Assembly: MT5Trade, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 8045A2CB-DBD6-41AD-8804-F98CAC1BDC8D
// Assembly location: C:\projects\trade\trade_tool\trade0812\MT5Trade.dll

using Commom.Util;
using MT5Trade.Models;
using MT5Trade.Services;
using MtApi5;
using MTTrade.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;

namespace MT5Trade;

public partial class MtTrade5 : Form
{
    private static object lock_obj = new object();
    private string filePath = string.Empty;
    private const int MaxLines = 1000;
    private List<TradeModel> trades;
    private ConcurrentDictionary<ulong, TradeInfo> orders_info = new ConcurrentDictionary<ulong, TradeInfo>();
    private ConcurrentDictionary<ulong, List<ENUM_TRADE_TRANSACTION_TYPE>> orders_check = new ConcurrentDictionary<ulong, List<ENUM_TRADE_TRANSACTION_TYPE>>();
    private MtApi5Client MtClientMain;
    private int portMain;
    private bool IsStartMain;
    public MtApi5Client MtClientFollow;
    private int portFollow;
    private bool IsStartFollow;
    
    // 依赖注入容器
    private IServiceProvider serviceProvider;

    // Kelly公式优化组件
    private KellyCalculator kellyCalculator;
    private HistoricalAnalyzer historicalAnalyzer;
    
    // 破产概率模型组件  
    private BankruptcyModel bankruptcyModel;
    
    // 杠杆控制器组件
    private LeverageController leverageController;
    
    // NSGA-II多目标优化组件
    private NSGA2Optimizer nsga2Optimizer;

    // 自适应对冲优化器和敏感性分析器
    private AdaptiveHedgeOptimizer adaptiveHedgeOptimizer;
    private SobolSensitivityAnalyzer sobolSensitivityAnalyzer;
    private PoissonRetryExecutor poissonRetryExecutor;
    private RiskControlMatrix riskControlMatrix;
    private RealTimeMonitor realTimeMonitor;
    private CircuitBreaker circuitBreaker;
    private GapHedgingStrategy gapHedgingStrategy;
    private DynamicHedgeAdjuster dynamicHedgeAdjuster;
    private BonusArbitrageOptimizer bonusArbitrageOptimizer;
    private DynamicGapAdjuster dynamicGapAdjuster;
    private TradingModeController tradingModeController;
    private CombinedPnLService combinedPnLService;

    // Kelly公式配置参数
    private bool enableKellyOptimization = true; // 启用Kelly优化的开关
    private double kellySafetyFactor = 0.25; // Kelly公式安全系数，默认25%
    private double maxPositionSize = 10.0; // 最大仓位限制
    private double minPositionSize = 0.01; // 最小仓位限制
    private int historicalAnalysisWindow = 30; // 历史数据分析窗口（天数）

    // 赠金套利配置参数
    private bool enableBonusArbitrage = true; // 启用赠金套利的开关
    private double bonusAmount = 500.0; // 初始赠金金额（美元）
    private double bonusRemaining = 500.0; // 剩余赠金金额（美元）
    private double targetGapRatio = 0.08; // 目标敞口比例（8%）
    private bool useAIOptimizedGap = true; // 使用AI优化的动态敞口
    
    // 杠杆控制配置参数
    private bool enableLeverageOptimization = true; // 启用杠杆优化的开关
    private double currentLeverageRatio = 100.0; // 当前杠杆比例，默认1:100
    private double maxBankruptcyProbability = 0.05; // 最大破产概率阈值（5%）
    private double expectedMarketReturn = 0.001; // 预期市场收益率（0.1%）
    private double marketVolatility = 0.015; // 市场波动率（1.5%）
    
    // NSGA-II多目标优化配置参数
    private bool enableNSGA2Optimization = true; // 启用NSGA-II多目标优化的开关
    private bool enableAutomaticParameterTuning = true; // 启用参数自动调优
    private int nsga2PopulationSize = NSGA2Optimizer.DEFAULT_POPULATION_SIZE; // NSGA-II种群大小，默认100
    private int nsga2MaxGenerations = NSGA2Optimizer.DEFAULT_MAX_GENERATIONS; // NSGA-II最大迭代代数，默认200
    private int optimizationUpdateIntervalMinutes = 30; // 参数优化更新间隔（分钟）
    private DateTime lastOptimizationTime = DateTime.MinValue; // 上次优化时间
    
    // 仓位计算模式枚举
    private enum PositionCalculationMode
    {
        FixedIncrement, // 原始固定增量模式
        KellyOptimized  // Kelly公式优化模式
    }

    private PositionCalculationMode positionMode = PositionCalculationMode.KellyOptimized;

    // 止盈止损配置参数
    private bool enableTakeProfit = true;              // 启用止盈的开关
    private bool enableStopLoss = true;                // 启用止损的开关
    private string takeProfitMode = "ATR";             // 止盈模式: Percentage/Points/ATR
    private double takeProfitValue = 2.0;              // 止盈值(根据模式不同含义不同)
    private string stopLossMode = "ATR";               // 止损模式: Percentage/Points/ATR
    private double stopLossValue = 1.0;                // 止损值(根据模式不同含义不同)
    private bool useTrailingStop = false;              // 是否使用移动止损
    private int magicNumber = 12345;                   // EA魔术号

    // 主账号止盈止损配置（独立于从账号设置）
    private bool mainEnableTakeProfit = false;         // 主账号是否启用止盈
    private bool mainEnableStopLoss = false;           // 主账号是否启用止损
    private string mainTakeProfitMode = "ATR";         // 主账号止盈模式
    private double mainTakeProfitValue = 2.0;          // 主账号止盈值
    private string mainStopLossMode = "ATR";           // 主账号止损模式
    private double mainStopLossValue = 1.0;            // 主账号止损值

    // 组合盈亏监控配置参数
    private bool enableCombinedPnL = false;            // 启用组合盈亏监控
    private double combinedTargetProfit = 100.0;       // 目标净利润（美元）
    private double combinedSafetyFactor = 1.05;        // 安全系数
    private int combinedCheckInterval = 100;           // 检查间隔（毫秒）
    private bool isMonitoringCombinedPnL = false;      // 监控状态标志
    private CancellationTokenSource? combinedMonitoringCts; // 监控任务取消令牌

    // ATR计算器（用于止盈止损计算）
    private ATRCalculator _atrCalculator;
    private RiskMetrics _riskMetrics;

    public MtTrade5()
    {
        // 初始化依赖注入容器
        InitializeDependencyInjection();
        
        // 从容器获取服务实例
        this.kellyCalculator = serviceProvider.GetRequiredService<KellyCalculator>();
        this.historicalAnalyzer = serviceProvider.GetRequiredService<HistoricalAnalyzer>();
        this.bankruptcyModel = serviceProvider.GetRequiredService<BankruptcyModel>();
        this.leverageController = serviceProvider.GetRequiredService<LeverageController>();
        this.nsga2Optimizer = serviceProvider.GetRequiredService<NSGA2Optimizer>();

        // 获取新的优化组件
        this.adaptiveHedgeOptimizer = serviceProvider.GetRequiredService<AdaptiveHedgeOptimizer>();
        this.sobolSensitivityAnalyzer = serviceProvider.GetRequiredService<SobolSensitivityAnalyzer>();
        this.poissonRetryExecutor = serviceProvider.GetRequiredService<PoissonRetryExecutor>();
        this.circuitBreaker = serviceProvider.GetRequiredService<CircuitBreaker>();
        this.gapHedgingStrategy = serviceProvider.GetRequiredService<GapHedgingStrategy>();
        this.dynamicHedgeAdjuster = serviceProvider.GetRequiredService<DynamicHedgeAdjuster>();
        this.bonusArbitrageOptimizer = serviceProvider.GetRequiredService<BonusArbitrageOptimizer>();
        this.dynamicGapAdjuster = serviceProvider.GetRequiredService<DynamicGapAdjuster>();
        this.riskControlMatrix = serviceProvider.GetRequiredService<RiskControlMatrix>();
        this.realTimeMonitor = serviceProvider.GetRequiredService<RealTimeMonitor>();
        this.tradingModeController = serviceProvider.GetRequiredService<TradingModeController>();
        this.combinedPnLService = serviceProvider.GetRequiredService<CombinedPnLService>();

        // 启动实时监控系统
        this.realTimeMonitor.StartMonitoring();

        // 配置NSGA-II算法参数
        if (enableNSGA2Optimization)
        {
            this.nsga2Optimizer.ConfigureAlgorithmParameters(nsga2PopulationSize, nsga2MaxGenerations);
        }
        
        this.InitializeComponent();
        this.directe.SelectedIndex = 1;  // 默认选择"正向"模式，而不是"反向"
        this.suffix.Text = JsonConvert.SerializeObject((object)new Dictionary<string, string>()
    {
      {
        "XAUUSD",
        "XAUUSD"
      },
      {
        "BTCUSD",
        "BTCUSD"
      },
      {
        "EURUSD",
        "EURUSD"
      }
    }, Formatting.Indented);
    }
    
    /// <summary>
    /// 初始化依赖注入容器
    /// </summary>
    private void InitializeDependencyInjection()
    {
        var services = new ServiceCollection();
        
        // 注册风险管理组件
        services.AddSingleton<RiskMetrics>();
        services.AddSingleton<KellyCalculator>();
        services.AddSingleton<HistoricalAnalyzer>();
        services.AddSingleton<BankruptcyModel>();
        services.AddSingleton<LeverageController>(sp => new LeverageController(currentLeverageRatio));
        
        // 注册模型组件
        services.AddSingleton<GarchModel>();
        services.AddSingleton<IRandomProvider, DeterministicRandomProvider>(sp => 
            DeterministicRandomProvider.CreateForOptimization($"MT5Trade_{DateTime.Today:yyyyMMdd}"));
        
        // 注册优化组件
        services.AddSingleton<NSGA2Optimizer>(sp =>
        {
            var historicalAnalyzer = sp.GetRequiredService<HistoricalAnalyzer>();
            var riskMetrics = sp.GetRequiredService<RiskMetrics>();
            var kellyCalculator = sp.GetRequiredService<KellyCalculator>();
            var garchModel = sp.GetRequiredService<GarchModel>();
            var randomProvider = sp.GetRequiredService<IRandomProvider>();
            
            return new NSGA2Optimizer(historicalAnalyzer, riskMetrics, kellyCalculator, garchModel, randomProvider);
        });
        
        // 注册重试和熔断机制
        services.AddSingleton<PoissonRetryExecutor>(sp =>
        {
            var randomProvider = sp.GetRequiredService<IRandomProvider>();
            return new PoissonRetryExecutor(randomProvider: randomProvider);
        });
        services.AddSingleton<CircuitBreaker>();

        // 注册风控和监控组件
        services.AddSingleton<RiskControlMatrix>(sp =>
            new RiskControlMatrix(RiskControlMatrix.RiskLevel.Moderate));
        services.AddSingleton<RealTimeMonitor>();

        // 注册对冲策略组件
        services.AddSingleton<GapHedgingStrategy>();
        services.AddSingleton<BetaCalculator>();
        services.AddSingleton<DynamicHedgeAdjuster>();

        // 注册赠金套利优化组件
        services.AddSingleton<BonusArbitrageOptimizer>();
        services.AddSingleton<DynamicGapAdjuster>();

        // 注册组合盈亏服务
        services.AddSingleton<CombinedPnLService>();
        services.AddSingleton<CombinedPnLSettings>();

        // 注册交易模式控制器
        services.AddSingleton<TradingModeController>();

        // 注册Sobol敏感性分析器
        services.AddSingleton<SobolSensitivityAnalyzer>(sp =>
        {
            var randomProvider = sp.GetRequiredService<IRandomProvider>();
            return new SobolSensitivityAnalyzer(randomProvider);
        });

        // 注册自适应对冲优化器
        services.AddSingleton<AdaptiveHedgeOptimizer>(sp =>
        {
            var garchModel = sp.GetRequiredService<GarchModel>();
            var kellyCalculator = sp.GetRequiredService<KellyCalculator>();
            var riskMetrics = sp.GetRequiredService<RiskMetrics>();
            var bankruptcyModel = sp.GetRequiredService<BankruptcyModel>();
            var leverageController = sp.GetRequiredService<LeverageController>();
            var nsga2Optimizer = sp.GetRequiredService<NSGA2Optimizer>();
            var gapHedgingStrategy = sp.GetRequiredService<GapHedgingStrategy>();
            var dynamicHedgeAdjuster = sp.GetRequiredService<DynamicHedgeAdjuster>();

            return new AdaptiveHedgeOptimizer(
                garchModel,
                kellyCalculator,
                riskMetrics,
                bankruptcyModel,
                leverageController,
                nsga2Optimizer,
                gapHedgingStrategy,
                dynamicHedgeAdjuster
            );
        });

        // 构建服务容器
        serviceProvider = services.BuildServiceProvider();
    }

    private void MtTrade5_Load(
#nullable enable
    object sender, EventArgs e)
    {
        try
        {
            this.MtClientMain = new MtApi5Client();
            this.MtClientMain.ConnectionStateChanged += new EventHandler<Mt5ConnectionEventArgs>(this.MainApiClient_ConnectionStateChanged);
            this.MtClientMain.QuoteAdded += new EventHandler<Mt5QuoteEventArgs>(this.MainapiClient_QuoteAdded);
            this.MtClientMain.QuoteRemoved += new EventHandler<Mt5QuoteEventArgs>(this.MainapiClient_QuoteRemoved);
            this.MtClientMain.QuoteUpdate += new EventHandler<Mt5QuoteEventArgs>(this.MainapiClient_QuoteUpdated);
            this.MtClientMain.OnTradeTransaction += new EventHandler<Mt5TradeTransactionEventArgs>(this.MainapiClient_OnTradeTransaction);
            this.MtClientMain.OnBookEvent += new EventHandler<Mt5BookEventArgs>(this.MainapiClient_OnBookEvent);
            this.MtClientMain.OnLastTimeBar += new EventHandler<Mt5TimeBarArgs>(this.MainapiClient_OnLastTimeBar);
            this.MtClientMain.OnLockTicks += new EventHandler<Mt5LockTicksEventArgs>(this.MainapiClient_OnLockTicks);

            this.MtClientFollow = new MtApi5Client();
            this.MtClientFollow.ConnectionStateChanged += new EventHandler<Mt5ConnectionEventArgs>(this.FollowApiClient_ConnectionStateChanged);
            this.MtClientFollow.QuoteAdded += new EventHandler<Mt5QuoteEventArgs>(this.FollowapiClient_QuoteAdded);
            this.MtClientFollow.QuoteRemoved += new EventHandler<Mt5QuoteEventArgs>(this.FollowapiClient_QuoteRemoved);
            this.MtClientFollow.QuoteUpdate += new EventHandler<Mt5QuoteEventArgs>(this.FollowapiClient_QuoteUpdated);
            this.MtClientFollow.OnTradeTransaction += new EventHandler<Mt5TradeTransactionEventArgs>(this.FollowapiClient_OnTradeTransaction);
            this.MtClientFollow.OnBookEvent += new EventHandler<Mt5BookEventArgs>(this.FollowapiClient_OnBookEvent);
            this.MtClientFollow.OnLastTimeBar += new EventHandler<Mt5TimeBarArgs>(this.FollowapiClient_OnLastTimeBar);
            this.MtClientFollow.OnLockTicks += new EventHandler<Mt5LockTicksEventArgs>(this.FollowapiClient_OnLockTicks);

            // 初始化组合盈亏服务的MT5客户端
            if (this.combinedPnLService != null && this.MtClientMain != null && this.MtClientFollow != null)
            {
                this.combinedPnLService.InitializeClients(this.MtClientMain, this.MtClientFollow);
                this.ShowMsg("组合盈亏服务已初始化MT5客户端");
            }

            // 记录初始化成功
            this.ShowMsg("MtTrade5_Load: MtApi5客户端初始化成功");
            this.ShowMsg($"  MtClientMain: {(this.MtClientMain != null ? "已创建" : "NULL")}");
            this.ShowMsg($"  MtClientFollow: {(this.MtClientFollow != null ? "已创建" : "NULL")}");
        }
        catch (Exception ex)
        {
            this.ShowMsg($"MtTrade5_Load异常: {ex.Message}", LogEmuns.Error, ex);
        }
        string str = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
        if (!File.Exists(str))
            Directory.CreateDirectory(str);
        this.filePath = Path.Combine(str, "trade.json");
        this.trades = JsonFileHelper.ReadFromFile<List<TradeModel>>(this.filePath) ?? new List<TradeModel>();

        // 加载止盈止损配置
        LoadTradingConfiguration();

        // 初始化ATR计算器和风险度量
        _atrCalculator = new ATRCalculator();
        _riskMetrics = serviceProvider?.GetService<RiskMetrics>() ?? new RiskMetrics();

        // 初始化交易模式UI
        InitializeTradingModeUI();

        // 初始化主账号止盈止损UI
        InitializeMainTPSLUI();
    }

    /// <summary>
    /// 加载交易配置
    /// </summary>
    private void LoadTradingConfiguration()
    {
        try
        {
            // 从配置文件加载止盈止损设置
            enableTakeProfit = ConfigurationManager.AppSettings["EnableTakeProfit"]?.ToLower() == "true";
            enableStopLoss = ConfigurationManager.AppSettings["EnableStopLoss"]?.ToLower() == "true";
            takeProfitMode = ConfigurationManager.AppSettings["TakeProfitMode"] ?? "ATR";
            takeProfitValue = double.Parse(ConfigurationManager.AppSettings["TakeProfitValue"] ?? "2.0");
            stopLossMode = ConfigurationManager.AppSettings["StopLossMode"] ?? "ATR";
            stopLossValue = double.Parse(ConfigurationManager.AppSettings["StopLossValue"] ?? "1.0");
            useTrailingStop = ConfigurationManager.AppSettings["UseTrailingStop"]?.ToLower() == "true";
            magicNumber = int.Parse(ConfigurationManager.AppSettings["MagicNumber"] ?? "12345");

            this.ShowMsg($"止盈止损配置已加载 - 止盈:{enableTakeProfit}/{takeProfitMode}/{takeProfitValue}, " +
                        $"止损:{enableStopLoss}/{stopLossMode}/{stopLossValue}", LogEmuns.Info);
        }
        catch (Exception ex)
        {
            this.ShowMsg($"加载止盈止损配置失败: {ex.Message}", LogEmuns.Error, ex);
            // 使用默认值
        }
    }

    private void btnMain_Click(object sender, EventArgs e)
    {
        try
        {
            this.ShowMsg($"点击主账号连接按钮，端口输入: {this.txtMainport.Text}");
            this.portMain = this.txtMainport.Text.ToInt();

            if (!this.IsStartMain)
            {
                this.ShowMsg($"启动主账号连接任务，端口: {this.portMain}");
                Task.Run((Func<Task>)(() =>
                {
                    while (true)
                    {
                        this.ConnectMain();
                        Thread.Sleep(5000);
                    }
                }));
                this.IsStartMain = true;
                this.ShowMsg("主账号连接任务已启动");
            }
            else
            {
                string str = "主账号连接任务已在运行";
                int num = (int)MessageBox.Show(str);
                this.ShowMsg(str);
            }
        }
        catch (Exception ex)
        {
            this.ShowMsg($"点击主账号连接按钮时出错: {ex.Message}", LogEmuns.Error, ex);
            MessageBox.Show($"连接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ConnectMain()
    {
        try
        {
            // 检查客户端是否已初始化
            if (this.MtClientMain == null)
            {
                this.ShowMsg("错误: MtClientMain未初始化！正在初始化...", LogEmuns.Error);
                this.MtClientMain = new MtApi5Client();
                this.MtClientMain.ConnectionStateChanged += new EventHandler<Mt5ConnectionEventArgs>(this.MainApiClient_ConnectionStateChanged);
                this.MtClientMain.OnTradeTransaction += new EventHandler<Mt5TradeTransactionEventArgs>(this.MainapiClient_OnTradeTransaction);
                this.ShowMsg("MtClientMain已重新初始化并订阅事件");
            }

            // 检查连接状态和健康度
            if (this.MtClientMain.ConnectionState == Mt5ConnectionState.Connected)
            {
                // 进一步检查连接是否真正健康
                if (IsConnectionHealthy(this.MtClientMain, "主账号"))
                {
                    // 连接健康，静默返回
                    return;
                }
                else
                {
                    // 连接不健康，断开重连
                    this.ShowMsg("主账号连接不健康，尝试重新连接", LogEmuns.Warn);
                    this.MtClientMain.BeginDisconnect();
                    Thread.Sleep(1000);
                }
            }

            // 只在真正需要连接时输出日志
            if (this.MtClientMain.ConnectionState == Mt5ConnectionState.Disconnected)
            {
                this.ShowMsg($"主账号开始连接到端口 {this.portMain}...");
                this.MtClientMain.BeginConnect(this.portMain);
            }
        }
        catch (Exception ex)
        {
            this.ShowMsg($"主账号连接异常: {ex.Message}", LogEmuns.Error, ex);
            this.ShowMsg($"异常类型: {ex.GetType().Name}", LogEmuns.Error);
            if (ex.InnerException != null)
            {
                this.ShowMsg($"内部异常: {ex.InnerException.Message}", LogEmuns.Error);
            }
            this.ShowMsg($"堆栈: {ex.StackTrace}", LogEmuns.Error);
        }
    }

    private void MainApiClient_ConnectionStateChanged(object? sender, Mt5ConnectionEventArgs e)
    {
        this.RunOnUiThread((Action)(() =>
        {
            switch (e.Status)
            {
                case Mt5ConnectionState.Connecting:
                    this.ShowMsg("主账号连接中...");
                    break;
                case Mt5ConnectionState.Connected:
                    this.ShowMsg("主账号已连接", LogEmuns.Success);
                    break;
                case Mt5ConnectionState.Disconnected:
                    this.ShowMsg("主账号断开连接", LogEmuns.Warn);
                    break;
                case Mt5ConnectionState.Failed:
                    this.ShowMsg("主账号连接失败", LogEmuns.Error);
                    break;
            }
        }));
    }

    private void MainapiClient_QuoteAdded(object? sender, Mt5QuoteEventArgs e)
    {
    }

    private void MainapiClient_QuoteRemoved(object? sender, Mt5QuoteEventArgs e)
    {
    }

    private void MainapiClient_QuoteUpdated(object? sender, Mt5QuoteEventArgs e)
    {
        Mt5Quote quote = e.Quote;
    }

    private void MainapiClient_OnTradeTransaction(object? sender, Mt5TradeTransactionEventArgs e)
    {
        if (this.cbxLogs.Checked)
            this.ShowMsg($"主账号：OnTradeTransaction: ExpertHandle = {e.ExpertHandle}.{Environment.NewLine}Transaction = {e.Trans}.{Environment.NewLine}Request = {e.Request}.{Environment.NewLine}Result = {e.Result}.");
        lock (MtTrade5.lock_obj)
            this.OptTrade(e, this.MtClientFollow);
    }

    private void MainapiClient_OnBookEvent(object? sender, Mt5BookEventArgs e)
    {
    }

    private void MainapiClient_OnLastTimeBar(object? sender, Mt5TimeBarArgs e)
    {
    }

    private void MainapiClient_OnLockTicks(object? sender, Mt5LockTicksEventArgs e)
    {
    }

    private void btnFollow_Click(object sender, EventArgs e)
    {
        try
        {
            this.ShowMsg($"点击从账号连接按钮，端口输入: {this.txtFollowPort.Text}");
            this.portFollow = this.txtFollowPort.Text.ToInt();

            if (!this.IsStartFollow)
            {
                this.ShowMsg($"启动从账号连接任务，端口: {this.portFollow}");
                Task.Run((Func<Task>)(() =>
                {
                    while (true)
                    {
                        this.ConnectFollow();
                        Thread.Sleep(5000);
                    }
                }));
                this.IsStartFollow = true;
                this.ShowMsg("从账号连接任务已启动");
            }
            else
            {
                string str = "从账号连接任务已在运行";
                int num = (int)MessageBox.Show(str);
                this.ShowMsg(str);
            }
        }
        catch (Exception ex)
        {
            this.ShowMsg($"点击从账号连接按钮时出错: {ex.Message}", LogEmuns.Error, ex);
            MessageBox.Show($"连接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ConnectFollow()
    {
        try
        {
            // 检查客户端是否已初始化
            if (this.MtClientFollow == null)
            {
                this.ShowMsg("错误: MtClientFollow未初始化！正在初始化...", LogEmuns.Error);
                this.MtClientFollow = new MtApi5Client();
                this.MtClientFollow.ConnectionStateChanged += new EventHandler<Mt5ConnectionEventArgs>(this.FollowApiClient_ConnectionStateChanged);
                this.MtClientFollow.OnTradeTransaction += new EventHandler<Mt5TradeTransactionEventArgs>(this.FollowapiClient_OnTradeTransaction);
                this.ShowMsg("MtClientFollow已重新初始化并订阅事件");
            }

            // 检查连接状态和健康度
            if (this.MtClientFollow.ConnectionState == Mt5ConnectionState.Connected)
            {
                // 进一步检查连接是否真正健康
                if (IsConnectionHealthy(this.MtClientFollow, "从账号"))
                {
                    // 连接健康，静默返回
                    return;
                }
                else
                {
                    // 连接不健康，断开重连
                    this.ShowMsg("从账号连接不健康，尝试重新连接", LogEmuns.Warn);
                    this.MtClientFollow.BeginDisconnect();
                    Thread.Sleep(1000);
                }
            }

            // 只在真正需要连接时输出日志
            if (this.MtClientFollow.ConnectionState == Mt5ConnectionState.Disconnected)
            {
                this.ShowMsg($"从账号开始连接到端口 {this.portFollow}...");
                this.MtClientFollow.BeginConnect(this.portFollow);
            }
        }
        catch (Exception ex)
        {
            this.ShowMsg($"从账号连接异常: {ex.Message}", LogEmuns.Error, ex);
            this.ShowMsg($"异常类型: {ex.GetType().Name}", LogEmuns.Error);
            if (ex.InnerException != null)
            {
                this.ShowMsg($"内部异常: {ex.InnerException.Message}", LogEmuns.Error);
            }
            this.ShowMsg($"堆栈: {ex.StackTrace}", LogEmuns.Error);
        }
    }

    private void FollowApiClient_ConnectionStateChanged(object? sender, Mt5ConnectionEventArgs e)
    {
        this.RunOnUiThread((Action)(() =>
        {
            switch (e.Status)
            {
                case Mt5ConnectionState.Connecting:
                    this.ShowMsg("从账号连接中...");
                    break;
                case Mt5ConnectionState.Connected:
                    this.ShowMsg("从账号已连接", LogEmuns.Success);
                    break;
                case Mt5ConnectionState.Disconnected:
                    this.ShowMsg("从账号断开连接", LogEmuns.Warn);
                    break;
                case Mt5ConnectionState.Failed:
                    this.ShowMsg("从账号连接失败", LogEmuns.Error);
                    break;
            }
        }));
    }

    private void FollowapiClient_QuoteAdded(object? sender, Mt5QuoteEventArgs e)
    {
    }

    private void FollowapiClient_QuoteRemoved(object? sender, Mt5QuoteEventArgs e)
    {
    }

    private void FollowapiClient_QuoteUpdated(object? sender, Mt5QuoteEventArgs e)
    {
        Mt5Quote quote = e.Quote;
    }

    private void FollowapiClient_OnTradeTransaction(object? sender, Mt5TradeTransactionEventArgs e)
    {
        if (this.cbxLogs.Checked)
            this.ShowMsg($"从账号：OnTradeTransaction: ExpertHandle = {e.ExpertHandle}.{Environment.NewLine}Transaction = {e.Trans}.{Environment.NewLine}Request = {e.Request}.{Environment.NewLine}Result = {e.Result}.");
        lock (MtTrade5.lock_obj)
            this.OptTrade(e, this.MtClientMain, false);
    }

    private void FollowapiClient_OnBookEvent(object? sender, Mt5BookEventArgs e)
    {
    }

    private void FollowapiClient_OnLastTimeBar(object? sender, Mt5TimeBarArgs e)
    {
    }

    private void FollowapiClient_OnLockTicks(object? sender, Mt5LockTicksEventArgs e)
    {
    }

    /// <summary>
    /// 检查连接健康状态
    /// </summary>
    private bool IsConnectionHealthy(MtApi5Client client, string accountType)
    {
        try
        {
            if (client == null || client.ConnectionState != Mt5ConnectionState.Connected)
                return false;

            // 尝试获取账户信息验证连接是否真正工作
            double balance = client.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_BALANCE);
            return balance >= 0;
        }
        catch
        {
            this.ShowMsg($"{accountType}连接异常，将重新连接", LogEmuns.Warn);
            return false;
        }
    }

    private void RunOnUiThread(Action action)
    {
        if (this.IsDisposed)
            return;
        this.BeginInvoke(action);
    }

    public void ShowMsg(string msg, LogEmuns logType = LogEmuns.Info, Exception ex = null)
    {
        this.RunOnUiThread((Action)(() =>
        {
            if (this.richTextBoxLog.Lines.Length > 1000)
                this.richTextBoxLog.Text = string.Join(Environment.NewLine, ((IEnumerable<string>)this.richTextBoxLog.Lines).Skip<string>(100).ToArray<string>()) + Environment.NewLine;
            switch (logType)
            {
                case LogEmuns.Info:
                    this.richTextBoxLog.SelectionColor = Color.Black;
                    break;
                case LogEmuns.Debug:
                    this.richTextBoxLog.SelectionColor = Color.Orange;
                    break;
                case LogEmuns.Warn:
                    this.richTextBoxLog.SelectionColor = Color.Yellow;
                    break;
                case LogEmuns.Error:
                    this.richTextBoxLog.SelectionColor = Color.Red;
                    break;
                case LogEmuns.Success:
                    this.richTextBoxLog.SelectionColor = Color.Green;
                    break;
            }
            this.richTextBoxLog.AppendText($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{logType}]: {msg}\n");
            this.richTextBoxLog.SelectionColor = this.richTextBoxLog.ForeColor;
            this.richTextBoxLog.ScrollToCaret();
            Task.Run((Action)(() =>
            {
                switch (logType)
                {
                    case LogEmuns.Info:
                    case LogEmuns.Success:
                        NLogger.Info(msg ?? "");
                        break;
                    case LogEmuns.Debug:
                        NLogger.Debug(msg ?? "");
                        break;
                    case LogEmuns.Warn:
                        NLogger.Warn(msg ?? "");
                        break;
                    case LogEmuns.Error:
                        if (ex != null)
                        {
                            NLogger.Error(ex);
                            break;
                        }
                        NLogger.Error(msg ?? "");
                        break;
                    default:
                        NLogger.Info(msg ?? "");
                        break;
                }
            }));
        }));
    }

    private void OptTrade(Mt5TradeTransactionEventArgs e, MtApi5Client mtClient, bool isMain = true)
    {
        try
        {
            if (e.Trans != null && e.Trans.Type == ENUM_TRADE_TRANSACTION_TYPE.TRADE_TRANSACTION_HISTORY_ADD)
            {
                if (!this.orders_info.ContainsKey(e.Trans.Order))
                {
                    TradeInfo tradeInfo = new TradeInfo()
                    {
                        symbol = e.Trans.Symbol,
                        order = e.Trans.Order,
                        direction = e.Trans.OrderType
                    };
                    if ((long)e.Trans.Position == (long)e.Trans.Order)
                    {
                        tradeInfo.type = "open";
                    }
                    else
                    {
                        tradeInfo.type = "close";
                        tradeInfo.c_order = e.Trans.Position;
                    }
                    this.orders_info.TryAdd(e.Trans.Order, tradeInfo);
                }
                else
                {
                    TradeInfo tradeInfo = this.orders_info[e.Trans.Order];
                    if ((long)e.Trans.Position == (long)e.Trans.Order)
                    {
                        tradeInfo.type = "open";
                    }
                    else
                    {
                        tradeInfo.type = "close";
                        tradeInfo.c_order = e.Trans.Position;
                    }
                    this.orders_info[e.Trans.Order] = tradeInfo;
                }
                if (this.orders_check.ContainsKey(e.Trans.Order))
                {
                    this.orders_check[e.Trans.Order].Add(ENUM_TRADE_TRANSACTION_TYPE.TRADE_TRANSACTION_HISTORY_ADD);
                }
                else
                {
                    int num = 1;
                    List<ENUM_TRADE_TRANSACTION_TYPE> list = new List<ENUM_TRADE_TRANSACTION_TYPE>(num);
                    CollectionsMarshal.SetCount<ENUM_TRADE_TRANSACTION_TYPE>(list, num);
                    CollectionsMarshal.AsSpan<ENUM_TRADE_TRANSACTION_TYPE>(list)[0] = ENUM_TRADE_TRANSACTION_TYPE.TRADE_TRANSACTION_HISTORY_ADD;
                    List<ENUM_TRADE_TRANSACTION_TYPE> tradeTransactionTypeList = list;
                    this.orders_check.TryAdd(e.Trans.Order, tradeTransactionTypeList);
                }
                this.DealOrder(e.Trans.Order, mtClient, isMain);
            }
            if (e.Result == null || e.Result.Request_id <= 0U)
                return;
            if (!this.orders_info.ContainsKey(e.Result.Order))
            {
                TradeInfo tradeInfo = new TradeInfo()
                {
                    volume = e.Result.Volume,
                    order = e.Result.Order,
                    symbol = e.Request.Symbol,
                    direction = e.Request.Type
                };
                this.orders_info.TryAdd(tradeInfo.order, tradeInfo);
            }
            else
                this.orders_info[e.Result.Order].volume = e.Result.Volume;
            if (this.orders_check.ContainsKey(e.Result.Order))
            {
                this.orders_check[e.Result.Order].Add(ENUM_TRADE_TRANSACTION_TYPE.TRADE_TRANSACTION_REQUEST);
            }
            else
            {
                int num = 1;
                List<ENUM_TRADE_TRANSACTION_TYPE> list = new List<ENUM_TRADE_TRANSACTION_TYPE>(num);
                CollectionsMarshal.SetCount<ENUM_TRADE_TRANSACTION_TYPE>(list, num);
                CollectionsMarshal.AsSpan<ENUM_TRADE_TRANSACTION_TYPE>(list)[0] = ENUM_TRADE_TRANSACTION_TYPE.TRADE_TRANSACTION_REQUEST;
                List<ENUM_TRADE_TRANSACTION_TYPE> tradeTransactionTypeList = list;
                this.orders_check.TryAdd(e.Result.Order, tradeTransactionTypeList);
            }
            this.DealOrder(e.Result.Order, mtClient, isMain);
        }
        catch (Exception ex)
        {
            this.ShowMsg("成交回报处理数据异常：" + ex.Message, LogEmuns.Error, ex);
        }
    }

    private void DealOrder(ulong order, MtApi5Client mtClient, bool isMain = true)
    {
        if (this.orders_info.ContainsKey(order))
        {
            TradeInfo tradeInfo1 = this.orders_info[order];
            if (tradeInfo1.type == "close")
            {
                try
                {
                    ulong orderid = tradeInfo1.c_order;
                    ulong ticket = 0;
                    TradeModel tradeModel;
                    if (isMain)
                    {
                        tradeModel = this.trades.FirstOrDefault<TradeModel>((Func<TradeModel, bool>)(o => (long)o.m_ticket == (long)orderid));
                        if (tradeModel != null && tradeModel.f_status == TradeStatus.open)
                            ticket = tradeModel.f_ticket;
                    }
                    else
                    {
                        tradeModel = this.trades.FirstOrDefault<TradeModel>((Func<TradeModel, bool>)(o => (long)o.f_ticket == (long)orderid));
                        if (tradeModel != null && tradeModel.m_status == TradeStatus.open)
                            ticket = tradeModel.m_ticket;
                    }
                    if (ticket <= 0UL)
                        return;
                    int num = 0;
                    while (num < 3)
                    {
                        MqlTradeResult result = (MqlTradeResult)null;
                        if (mtClient.PositionClose(ticket, out result))
                        {
                            tradeModel.m_status = TradeStatus.close;
                            tradeModel.f_status = TradeStatus.close;
                            this.orders_info.TryRemove(tradeInfo1.order, out TradeInfo _);
                            this.orders_check.TryRemove(tradeInfo1.order, out List<ENUM_TRADE_TRANSACTION_TYPE> _);
                            this.ShowMsg($"【平仓】主订单号: {orderid},从订单号:{ticket}【平仓成功】", LogEmuns.Success);
                            break;
                        }
                        ++num;
                        this.ShowMsg($"【平仓】主订单号: {orderid},从订单号:{ticket}【平仓失败】错误码:{result.Retcode},开始第{num}次重试", LogEmuns.Error);
                        Thread.Sleep(150);
                    }
                }
                catch (Exception ex)
                {
                    this.ShowMsg("【平仓】系统异常: " + ex.Message, LogEmuns.Error, ex);
                }
            }
            else
            {
                List<ENUM_TRADE_TRANSACTION_TYPE> checks_order_types = this.orders_check[order];
                int num1 = 2;
                List<ENUM_TRADE_TRANSACTION_TYPE> tradeTransactionTypeList = new List<ENUM_TRADE_TRANSACTION_TYPE>(num1);
                CollectionsMarshal.SetCount<ENUM_TRADE_TRANSACTION_TYPE>(tradeTransactionTypeList, num1);
                Span<ENUM_TRADE_TRANSACTION_TYPE> span = CollectionsMarshal.AsSpan<ENUM_TRADE_TRANSACTION_TYPE>(tradeTransactionTypeList);
                int index1 = 0;
                span[index1] = ENUM_TRADE_TRANSACTION_TYPE.TRADE_TRANSACTION_REQUEST;
                int index2 = index1 + 1;
                span[index2] = ENUM_TRADE_TRANSACTION_TYPE.TRADE_TRANSACTION_HISTORY_ADD;
                if (!tradeTransactionTypeList.All<ENUM_TRADE_TRANSACTION_TYPE>((Func<ENUM_TRADE_TRANSACTION_TYPE, bool>)(a => checks_order_types.Contains(a))))
                    return;
                if (this.orders_info.ContainsKey(order))
                {
                    TradeInfo tradeInfo2 = this.orders_info[order];
                    if (!(tradeInfo2.type == "open") || !isMain)
                        return;
                    long num2 = (long)this.OpenOrderAdvanced(tradeInfo2, mtClient);
                }
                else
                    this.ShowMsg($"订单{order} 不存在", LogEmuns.Error);
            }
        }
        else
            this.ShowMsg($"订单{order} 不存在", LogEmuns.Error);
    }

    private void MtTrade5_FormClosing(object sender, FormClosingEventArgs e)
    {
        this.MtClientMain.BeginDisconnect();
        this.MtClientFollow.BeginDisconnect();
        this.trades.RemoveAll((Predicate<TradeModel>)(a => a.m_status == TradeStatus.close && a.f_status == TradeStatus.close));
        JsonFileHelper.WriteToFile<List<TradeModel>>(this.filePath, this.trades);
    }

    /// <summary>
    /// 计算Kelly优化的仓位大小
    /// </summary>
    /// <param name="tradeInfo">交易信息</param>
    /// <param name="baseVolume">基础仓位大小</param>
    /// <param name="mtClient">MT5客户端，用于获取账户信息</param>
    /// <returns>优化后的仓位大小</returns>
    private double CalculateKellyOptimizedPosition(TradeInfo tradeInfo, double baseVolume, MtApi5Client mtClient)
    {
        try
        {
            // 如果未启用Kelly优化，使用原始固定增量模式
            if (!enableKellyOptimization || positionMode == PositionCalculationMode.FixedIncrement)
            {
                double fixedIncrement = this.txtBs.Text.ToStr().ToDouble();
                return Math.Round(baseVolume + fixedIncrement, 2);
            }

            // 获取历史交易数据进行分析
            var symbolTrades = this.trades.Where(t => 
                t.Symbol?.ToUpper() == tradeInfo.symbol?.ToUpper() && 
                t.CloseTime > DateTime.Now.AddDays(-historicalAnalysisWindow)
            ).ToList();

            // 如果历史数据不足，使用保守的Kelly系数
            if (symbolTrades.Count < HistoricalAnalyzer.MIN_SAMPLE_SIZE)
            {
                this.ShowMsg($"【Kelly仓位优化】货币对 {tradeInfo.symbol} 历史数据不足({symbolTrades.Count}笔)，使用保守Kelly系数", LogEmuns.Warn);
                double conservativePosition = baseVolume * kellySafetyFactor;
                return Math.Max(minPositionSize, Math.Min(maxPositionSize, Math.Round(conservativePosition, 2)));
            }

            // 清洗历史数据并计算Kelly参数
            var cleanedTrades = historicalAnalyzer.CleanHistoricalData(symbolTrades);
            var kellyParams = historicalAnalyzer.GetKellyParameters(cleanedTrades);

            // 计算Kelly最优仓位比例
            double kellyFraction = kellyCalculator.CalculateOptimalKellyFraction(
                kellyParams.WinRate,
                kellyParams.OddsRatio
            );

            // 应用安全系数
            double safeKellyFraction = kellyFraction * kellySafetyFactor;

            // 获取实际账户余额
            double accountBalance = GetAccountBalance(mtClient);

            // 获取交易品种的价格基准
            double priceBase = GetSymbolPriceBase(tradeInfo.symbol, mtClient);

            // 计算最优仓位大小
            double optimalPosition = kellyCalculator.GetOptimalPositionSize(
                accountBalance,
                kellyParams.WinRate,
                kellyParams.OddsRatio,
                kellySafetyFactor,
                minPositionSize,
                maxPositionSize
            );

            // 应用仓位限制
            double finalPosition = Math.Max(minPositionSize, 
                Math.Min(maxPositionSize, Math.Round(optimalPosition, 2)));

            // 记录Kelly计算结果
            this.ShowMsg($"【Kelly仓位优化】货币对:{tradeInfo.symbol}, 胜率:{kellyParams.WinRate:P2}, " +
                        $"赔率:{kellyParams.OddsRatio:F2}, Kelly系数:{kellyFraction:F4}, " +
                        $"安全系数:{kellySafetyFactor:F2}, 最终仓位:{finalPosition:F2}", 
                        LogEmuns.Success);

            return finalPosition;
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【Kelly仓位优化】计算异常: {ex.Message}，回退到固定增量模式", LogEmuns.Error, ex);
            
            // 异常时回退到原始固定增量模式
            double fixedIncrement = this.txtBs.Text.ToStr().ToDouble();
            return Math.Round(baseVolume + fixedIncrement, 2);
        }
    }

    /// <summary>
    /// 计算赠金套利优化的敞口
    /// </summary>
    /// <param name="tradeInfo">交易信息</param>
    /// <param name="baseVolume">基础仓位大小</param>
    /// <param name="mtClient">MT5客户端</param>
    /// <param name="isMainAccount">是否为主账户（带赠金的XM账户）</param>
    /// <returns>优化后的仓位大小</returns>
    private double CalculateBonusArbitragePosition(TradeInfo tradeInfo, double baseVolume, MtApi5Client mtClient, bool isMainAccount)
    {
        try
        {
            // 主账户始终保持100%跟单
            if (isMainAccount)
            {
                return baseVolume;
            }

            // 使用交易模式控制器判断是否启用优化
            if (tradingModeController != null && tradingModeController.CurrentMode != TradingModeController.TradingMode.Manual)
            {
                // 收集市场数据用于优化
                var marketData = new
                {
                    Symbol = tradeInfo.symbol,
                    Price = GetSymbolPrice(tradeInfo.symbol, mtClient),
                    Spread = GetSymbolSpread(tradeInfo.symbol, mtClient),
                    AccountMargin = GetAccountMarginLevel(mtClient),
                    Volatility = CalculateMarketVolatility(tradeInfo.symbol, mtClient),
                    BonusRemaining = bonusRemaining,
                    MainLossProbability = EstimateMainAccountLossProbability(tradeInfo),
                    LastTradeWin = GetLastTradeResult(tradeInfo.symbol)
                };

                // 使用控制器计算优化敞口
                double optimalGap = tradingModeController.CalculateOptimalGap(
                    tradeInfo.symbol,
                    targetGapRatio,
                    marketData
                );

                // 计算最终仓位
                double finalPosition = Math.Round(baseVolume * optimalGap, 2);

                // 记录优化结果
                this.ShowMsg($"【{tradingModeController.GetModeDescription()}】货币对:{tradeInfo.symbol}, " +
                            $"剩余赠金:${bonusRemaining:F0}, 优化敞口:{optimalGap:P1}, " +
                            $"最终仓位:{finalPosition:F2}",
                            LogEmuns.Success);

                return finalPosition;
            }
            else
            {
                // 手动模式或控制器未初始化，使用固定敞口
                double manualPosition = Math.Round(baseVolume * targetGapRatio, 2);

                this.ShowMsg($"【手动模式】货币对:{tradeInfo.symbol}, " +
                            $"固定敞口:{targetGapRatio:P1}, 最终仓位:{manualPosition:F2}",
                            LogEmuns.Success);

                return manualPosition;
            }
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【赠金套利优化】计算异常: {ex.Message}，使用默认敞口", LogEmuns.Error, ex);
            // 异常时使用默认敞口
            return isMainAccount ? baseVolume : Math.Round(baseVolume * targetGapRatio, 2);
        }
    }

    /// <summary>
    /// 估算主账户亏损概率（基于技术指标）
    /// </summary>
    private double EstimateMainAccountLossProbability(TradeInfo tradeInfo)
    {
        // 这里可以接入技术指标分析
        // 暂时返回基础概率70%
        return 0.70;
    }

    /// <summary>
    /// 获取最后一笔交易结果
    /// </summary>
    private bool GetLastTradeResult(string symbol)
    {
        var lastTrade = this.trades
            .Where(t => t.Symbol?.ToUpper() == symbol?.ToUpper())
            .OrderByDescending(t => t.CloseTime)
            .FirstOrDefault();

        return lastTrade != null && lastTrade.Profit > 0;
    }

    /// <summary>
    /// 计算市场波动率
    /// </summary>
    private double CalculateMarketVolatility(string symbol, MtApi5Client mtClient)
    {
        // 这里可以接入更复杂的波动率计算
        // 暂时返回默认值1.5%
        return 0.015;
    }

    /// <summary>
    /// 获取账户保证金水平
    /// </summary>
    private double GetAccountMarginLevel(MtApi5Client mtClient)
    {
        try
        {
            return mtClient.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_MARGIN_LEVEL) / 100.0;
        }
        catch
        {
            return 2.0; // 默认200%保证金水平
        }
    }

    /// <summary>
    /// 获取符号点差
    /// </summary>
    private double GetSymbolSpread(string symbol, MtApi5Client mtClient)
    {
        try
        {
            return mtClient.SymbolInfoInteger(symbol, ENUM_SYMBOL_INFO_INTEGER.SYMBOL_SPREAD) *
                   mtClient.SymbolInfoDouble(symbol, ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_POINT);
        }
        catch
        {
            return 2.0; // 默认2点点差
        }
    }

    /// <summary>
    /// 获取符号价格
    /// </summary>
    private double GetSymbolPrice(string symbol, MtApi5Client mtClient)
    {
        try
        {
            return mtClient.SymbolInfoDouble(symbol, ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_BID);
        }
        catch
        {
            return 1.0;
        }
    }

    /// <summary>
    /// 计算止盈价格
    /// </summary>
    private double CalculateTakeProfit(TradeInfo tradeInfo, double currentPrice, MtApi5Client mtClient, bool isMainAccount = false)
    {
        // 根据账号类型选择配置
        bool enabled = isMainAccount ? mainEnableTakeProfit : enableTakeProfit;
        string mode = isMainAccount ? mainTakeProfitMode : takeProfitMode;
        double value = isMainAccount ? mainTakeProfitValue : takeProfitValue;

        if (!enabled) return 0.0;

        double takeProfitDistance = 0.0;

        switch (mode)
        {
            case "Percentage":
                takeProfitDistance = currentPrice * (value / 100);
                break;

            case "Points":
                {
                    double point = mtClient.SymbolInfoDouble(tradeInfo.symbol,
                        ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_POINT);
                    takeProfitDistance = value * point;
                }
                break;

            case "ATR":
                // 使用已有的ATR计算器
                if (_atrCalculator != null && _atrCalculator.GetCurrentATR() > 0)
                {
                    double atr = _atrCalculator.GetCurrentATR();
                    takeProfitDistance = atr * value;
                }
                else
                {
                    // 后备方案：使用固定百分比
                    takeProfitDistance = currentPrice * 0.02;
                }
                break;

            case "Amount":  // 新增金额模式
                {
                    // 计算达到目标金额需要的价格距离
                    double tickValue = CalculateTickValue(tradeInfo.symbol, tradeInfo.volume, mtClient);
                    if (tickValue > 0)
                    {
                        double point = mtClient.SymbolInfoDouble(tradeInfo.symbol,
                            ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_POINT);
                        // 目标金额 / 每点价值 = 需要的点数
                        double requiredPoints = value / tickValue;
                        takeProfitDistance = requiredPoints * point;
                    }
                    else
                    {
                        // 后备方案：使用固定百分比
                        ShowMsg($"无法计算{tradeInfo.symbol}的点值，使用默认2%止盈", LogEmuns.Warn);
                        takeProfitDistance = currentPrice * 0.02;
                    }
                }
                break;

            default:
                takeProfitDistance = currentPrice * 0.02; // 默认2%
                break;
        }

        // 根据交易方向设置止盈
        if (tradeInfo.direction == ENUM_ORDER_TYPE.ORDER_TYPE_BUY)
        {
            return currentPrice + takeProfitDistance;
        }
        else
        {
            return currentPrice - takeProfitDistance;
        }
    }

    /// <summary>
    /// 计算止损价格
    /// </summary>
    private double CalculateStopLoss(TradeInfo tradeInfo, double currentPrice, MtApi5Client mtClient, bool isMainAccount = false)
    {
        // 根据账号类型选择配置
        bool enabled = isMainAccount ? mainEnableStopLoss : enableStopLoss;
        string mode = isMainAccount ? mainStopLossMode : stopLossMode;
        double value = isMainAccount ? mainStopLossValue : stopLossValue;

        if (!enabled) return 0.0;

        double stopLossDistance = 0.0;

        switch (mode)
        {
            case "Percentage":
                stopLossDistance = currentPrice * (value / 100);
                break;

            case "Points":
                {
                    double point = mtClient.SymbolInfoDouble(tradeInfo.symbol,
                        ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_POINT);
                    stopLossDistance = value * point;
                }
                break;

            case "ATR":
                // 使用已有的ATR计算器
                if (_atrCalculator != null && _atrCalculator.GetCurrentATR() > 0)
                {
                    double atr = _atrCalculator.GetCurrentATR();
                    stopLossDistance = atr * value;
                }
                else
                {
                    // 后备方案
                    stopLossDistance = currentPrice * 0.01;
                }
                break;

            case "Amount":  // 新增金额模式
                {
                    double tickValue = CalculateTickValue(tradeInfo.symbol, tradeInfo.volume, mtClient);
                    if (tickValue > 0)
                    {
                        double point = mtClient.SymbolInfoDouble(tradeInfo.symbol,
                            ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_POINT);
                        double requiredPoints = value / tickValue;
                        stopLossDistance = requiredPoints * point;
                    }
                    else
                    {
                        ShowMsg($"无法计算{tradeInfo.symbol}的点值，使用默认1%止损", LogEmuns.Warn);
                        stopLossDistance = currentPrice * 0.01;
                    }
                }
                break;

            default:
                stopLossDistance = currentPrice * 0.01; // 默认1%
                break;
        }

        // 根据交易方向设置止损
        if (tradeInfo.direction == ENUM_ORDER_TYPE.ORDER_TYPE_BUY)
        {
            return currentPrice - stopLossDistance;
        }
        else
        {
            return currentPrice + stopLossDistance;
        }
    }

    /// <summary>
    /// 计算每点价值（美元）
    /// </summary>
    private double CalculateTickValue(string symbol, double volume, MtApi5Client mtClient)
    {
        try
        {
            // 获取品种信息
            double contractSize = mtClient.SymbolInfoDouble(symbol,
                ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_TRADE_CONTRACT_SIZE);
            double tickSize = mtClient.SymbolInfoDouble(symbol,
                ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_TRADE_TICK_SIZE);
            double tickValue = mtClient.SymbolInfoDouble(symbol,
                ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_TRADE_TICK_VALUE);

            if (contractSize <= 0) contractSize = 100000;  // 默认标准手

            // 对于外汇品种的特殊处理
            if (symbol.Contains("USD"))
            {
                if (symbol.StartsWith("USD"))
                {
                    // USDJPY等，USD在前
                    double price = mtClient.SymbolInfoDouble(symbol, ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_BID);
                    return volume * contractSize * tickSize / price;
                }
                else
                {
                    // EURUSD等，USD在后
                    return volume * contractSize * tickSize;
                }
            }
            else
            {
                // 其他品种，使用MT5提供的tick value
                return volume * tickValue;
            }
        }
        catch (Exception ex)
        {
            ShowMsg($"计算点值失败: {ex.Message}", LogEmuns.Error, ex);
            return 0;
        }
    }

    private ulong OpenOrder(TradeInfo tradeInfo, MtApi5Client mtClient)
    {
        try
        {
            this.ShowMsg("数据：" + tradeInfo.ToJson());

            // 检查客户端连接状态
            if (mtClient == null)
            {
                this.ShowMsg("【开仓失败】客户端为NULL", LogEmuns.Error);
                return 0;
            }

            if (mtClient.ConnectionState != Mt5ConnectionState.Connected)
            {
                this.ShowMsg($"【开仓失败】客户端未连接，状态:{mtClient.ConnectionState}", LogEmuns.Error);
                return 0;
            }

            // 使用Kelly公式优化的仓位计算替代固定增量计算
            double volume = CalculateKellyOptimizedPosition(tradeInfo, tradeInfo.volume, mtClient);
            Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.suffix.Text.ToStr());
            string symbol = "";
            string upper = tradeInfo.symbol.ToUpper();
            ref string local = ref symbol;
            if (!dictionary.TryGetValue(upper, out local))
            {
                this.ShowMsg($"货币对：{tradeInfo.symbol}，无任何映射,使用当前的货币对", LogEmuns.Error);
                symbol = tradeInfo.symbol;
            }
            // 验证品种是否可交易
            if (!mtClient.SymbolSelect(symbol, true))
            {
                this.ShowMsg($"【开仓失败】无法选择品种:{symbol}", LogEmuns.Error);
                return 0;
            }

            string propertyThreadSafe = MtTrade5.GetControlPropertyThreadSafe<string>((Control)this.directe, (Func<ComboBox, string>)(cmb => cmb.SelectedItem?.ToString()));
            int num2 = 0;
            while (num2 < 3)
            {
                MqlTradeResult result = (MqlTradeResult)null;
                if (!tradeInfo.direction.Equals((object)ENUM_ORDER_TYPE.ORDER_TYPE_BUY) ? (!(propertyThreadSafe == "正向") ? mtClient.Buy(out result, volume, symbol) : mtClient.Sell(out result, volume, symbol)) : (!(propertyThreadSafe == "正向") ? mtClient.Sell(out result, volume, symbol) : mtClient.Buy(out result, volume, symbol)))
                {
                    this.trades.Add(new TradeModel()
                    {
                        m_ticket = tradeInfo.order,
                        m_status = TradeStatus.open,
                        f_ticket = result.Order,
                        f_status = TradeStatus.open
                    });
                    this.ShowMsg($"【开仓】主订单号: {tradeInfo.order}, symbol:{tradeInfo.symbol},手数:{tradeInfo.volume};从订单号:{result.Order}，symbol:{symbol}，手数:{volume},【开仓成功】", LogEmuns.Success);
                    return result.Order;
                }
                ++num2;
                // 获取详细错误信息
                int lastError = mtClient.GetLastError();
                string errorDesc = GetMT5ErrorDescription(lastError);
                this.ShowMsg($"【开仓】主订单号: {tradeInfo.order}, symbol = {tradeInfo.symbol},手数:{tradeInfo.volume},从账号【开仓失败】,错误码：{result.Retcode}, MT5错误:{lastError}-{errorDesc},开始第{num2}次重试", LogEmuns.Error);
                Thread.Sleep(200);
            }
            this.ShowMsg($"【开仓】主订单号: {tradeInfo.order}, symbol = {tradeInfo.symbol},手数:{tradeInfo.volume},从账号【开仓失败】，重试多次都失败，请人工接入", LogEmuns.Error);
            return 0;
        }
        catch (Exception ex)
        {
            this.ShowMsg("【开仓】系统异常: " + ex.Message, LogEmuns.Error, ex);
            return 0;
        }
    }

    /// <summary>
    /// 使用OrderSend高级方法开仓，支持止盈止损
    /// </summary>
    private ulong OpenOrderAdvanced(TradeInfo tradeInfo, MtApi5Client mtClient)
    {
        try
        {
            this.ShowMsg("高级开仓数据：" + tradeInfo.ToJson());

            // 1. 检查客户端连接状态
            if (mtClient == null)
            {
                this.ShowMsg("【高级开仓失败】客户端为NULL", LogEmuns.Error);
                return 0;
            }

            if (mtClient.ConnectionState != Mt5ConnectionState.Connected)
            {
                this.ShowMsg($"【高级开仓失败】客户端未连接，状态:{mtClient.ConnectionState}", LogEmuns.Error);
                return 0;
            }

            // 2. 检查账户信息
            double balance = mtClient.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_BALANCE);
            double freeMargin = mtClient.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_MARGIN_FREE);
            double equity = mtClient.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_EQUITY);

            this.ShowMsg($"【账户信息】余额:{balance:F2}, 可用保证金:{freeMargin:F2}, 净值:{equity:F2}", LogEmuns.Info);

            if (freeMargin <= 0)
            {
                this.ShowMsg($"【高级开仓失败】可用保证金不足:{freeMargin:F2}", LogEmuns.Error);
                return 0;
            }

            // 计算交易量（使用现有的Kelly优化）
            double volume = CalculateKellyOptimizedPosition(tradeInfo, tradeInfo.volume, mtClient);

            // 获取品种映射
            Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(
                this.suffix.Text.ToStr());
            string symbol = "";
            string upper = tradeInfo.symbol.ToUpper();
            if (!dictionary.TryGetValue(upper, out symbol))
            {
                this.ShowMsg($"货币对：{tradeInfo.symbol}，无任何映射,使用当前的货币对", LogEmuns.Error);
                symbol = tradeInfo.symbol;
            }

            // 3. 验证品种是否可交易
            if (!mtClient.SymbolSelect(symbol, true))
            {
                this.ShowMsg($"【高级开仓失败】无法选择品种:{symbol}", LogEmuns.Error);
                return 0;
            }

            // 检查品种交易模式
            long tradeMode = mtClient.SymbolInfoInteger(symbol, ENUM_SYMBOL_INFO_INTEGER.SYMBOL_TRADE_MODE);
            if (tradeMode == 0) // SYMBOL_TRADE_MODE_DISABLED
            {
                this.ShowMsg($"【高级开仓失败】品种{symbol}交易被禁用", LogEmuns.Error);
                return 0;
            }

            // 获取当前价格
            double currentPrice = mtClient.SymbolInfoDouble(symbol,
                ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_ASK); // 买单用ASK
            if (tradeInfo.direction != ENUM_ORDER_TYPE.ORDER_TYPE_BUY)
            {
                currentPrice = mtClient.SymbolInfoDouble(symbol,
                    ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_BID); // 卖单用BID
            }

            if (currentPrice <= 0)
            {
                this.ShowMsg($"【高级开仓失败】无法获取品种{symbol}的价格", LogEmuns.Error);
                return 0;
            }

            // 获取交易方向设置
            string propertyThreadSafe = MtTrade5.GetControlPropertyThreadSafe<string>(
                (Control)this.directe, (Func<ComboBox, string>)(cmb => cmb.SelectedItem?.ToString()));

            // 确定实际交易类型（考虑正向/反向）
            ENUM_ORDER_TYPE actualOrderType = tradeInfo.direction;
            if (propertyThreadSafe == "反向")
            {
                actualOrderType = (tradeInfo.direction == ENUM_ORDER_TYPE.ORDER_TYPE_BUY)
                    ? ENUM_ORDER_TYPE.ORDER_TYPE_SELL
                    : ENUM_ORDER_TYPE.ORDER_TYPE_BUY;
            }

            // 构建交易请求
            var request = new MqlTradeRequest
            {
                Action = ENUM_TRADE_REQUEST_ACTIONS.TRADE_ACTION_DEAL,
                Symbol = symbol,
                Volume = volume,
                Type = actualOrderType,
                Price = 0.0,  // 0表示市价
                // OpenOrderAdvanced是在从账号上执行的，所以使用从账号配置
                Sl = CalculateStopLoss(tradeInfo, currentPrice, mtClient, false),
                Tp = CalculateTakeProfit(tradeInfo, currentPrice, mtClient, false),
                Deviation = 10,  // 允许滑点10点
                Type_filling = ENUM_ORDER_TYPE_FILLING.ORDER_FILLING_IOC,
                Type_time = ENUM_ORDER_TYPE_TIME.ORDER_TIME_GTC,
                Magic = (ulong)magicNumber,
                Comment = $"MT5Trade_Main:{tradeInfo.order}"
            };

            // 记录请求详情
            this.ShowMsg($"【高级开仓请求】品种:{request.Symbol}, 方向:{request.Type}, " +
                        $"手数:{request.Volume:F2}, 止损:{request.Sl:F5}, 止盈:{request.Tp:F5}",
                        LogEmuns.Info);

            // 4. 验证止损止盈的合理性
            if (request.Sl > 0 || request.Tp > 0)
            {
                this.ShowMsg($"【当前价格】{symbol}: {currentPrice:F5}", LogEmuns.Debug);

                // 验证止损止盈的方向
                bool isValidSLTP = true;

                if (request.Type == ENUM_ORDER_TYPE.ORDER_TYPE_BUY && request.Sl > 0)
                {
                    // 买单止损应该 < 当前价格
                    if (request.Sl >= currentPrice)
                    {
                        this.ShowMsg($"【参数错误】买单止损({request.Sl:F5})应该小于当前价格({currentPrice:F5})", LogEmuns.Error);
                        isValidSLTP = false;
                    }
                }

                if (request.Type == ENUM_ORDER_TYPE.ORDER_TYPE_BUY && request.Tp > 0)
                {
                    // 买单止盈应该 > 当前价格
                    if (request.Tp <= currentPrice)
                    {
                        this.ShowMsg($"【参数错误】买单止盈({request.Tp:F5})应该大于当前价格({currentPrice:F5})", LogEmuns.Error);
                        isValidSLTP = false;
                    }
                }

                if (request.Type == ENUM_ORDER_TYPE.ORDER_TYPE_SELL && request.Sl > 0)
                {
                    // 卖单止损应该 > 当前价格
                    if (request.Sl <= currentPrice)
                    {
                        this.ShowMsg($"【参数错误】卖单止损({request.Sl:F5})应该大于当前价格({currentPrice:F5})", LogEmuns.Error);
                        isValidSLTP = false;
                    }
                }

                if (request.Type == ENUM_ORDER_TYPE.ORDER_TYPE_SELL && request.Tp > 0)
                {
                    // 卖单止盈应该 < 当前价格
                    if (request.Tp >= currentPrice)
                    {
                        this.ShowMsg($"【参数错误】卖单止盈({request.Tp:F5})应该小于当前价格({currentPrice:F5})", LogEmuns.Error);
                        isValidSLTP = false;
                    }
                }

                if (!isValidSLTP)
                {
                    this.ShowMsg($"【高级开仓失败】止损止盈参数不合理，已取消订单", LogEmuns.Error);
                    return 0;
                }
            }

            // 5. 检查最小止损距离
            int stopsLevel = (int)mtClient.SymbolInfoInteger(symbol, ENUM_SYMBOL_INFO_INTEGER.SYMBOL_TRADE_STOPS_LEVEL);
            double point = mtClient.SymbolInfoDouble(symbol, ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_POINT);
            double minStopDistance = stopsLevel * point;

            this.ShowMsg($"【Broker要求】{symbol} 最小止损距离:{stopsLevel}点 = {minStopDistance:F5}", LogEmuns.Debug);

            if (minStopDistance > 0 && currentPrice > 0)
            {
                if (request.Sl > 0)
                {
                    double slDistance = Math.Abs(currentPrice - request.Sl);
                    if (slDistance < minStopDistance)
                    {
                        this.ShowMsg($"【高级开仓失败】止损距离({slDistance:F5})小于Broker要求的最小距离({minStopDistance:F5})", LogEmuns.Error);
                        return 0;
                    }
                }

                if (request.Tp > 0)
                {
                    double tpDistance = Math.Abs(currentPrice - request.Tp);
                    if (tpDistance < minStopDistance)
                    {
                        this.ShowMsg($"【高级开仓失败】止盈距离({tpDistance:F5})小于Broker要求的最小距离({minStopDistance:F5})", LogEmuns.Error);
                        return 0;
                    }
                }
            }

            // 6. 记录详细的请求参数
            this.ShowMsg($"【准备发送订单】", LogEmuns.Info);
            this.ShowMsg($"  品种: {request.Symbol}", LogEmuns.Debug);
            this.ShowMsg($"  动作: {request.Action}", LogEmuns.Debug);
            this.ShowMsg($"  类型: {request.Type}", LogEmuns.Debug);
            this.ShowMsg($"  手数: {request.Volume}", LogEmuns.Debug);
            this.ShowMsg($"  价格: {request.Price} (0表示市价)", LogEmuns.Debug);
            this.ShowMsg($"  止损: {request.Sl} (0表示不设置)", LogEmuns.Debug);
            this.ShowMsg($"  止盈: {request.Tp} (0表示不设置)", LogEmuns.Debug);
            this.ShowMsg($"  偏移: {request.Deviation}", LogEmuns.Debug);
            this.ShowMsg($"  魔法号: {request.Magic}", LogEmuns.Debug);
            this.ShowMsg($"  注释: {request.Comment}", LogEmuns.Debug);

            // 执行交易（带重试机制）
            int retryCount = 0;
            while (retryCount < 3)
            {
                MqlTradeResult result = null;
                if (mtClient.OrderSend(request, out result))
                {
                    if (result.Retcode == 10009 || result.Retcode == 10008) // 成功代码
                    {
                        // 添加到跟踪列表
                        this.trades.Add(new TradeModel()
                        {
                            m_ticket = tradeInfo.order,
                            m_status = TradeStatus.open,
                            f_ticket = result.Order,
                            f_status = TradeStatus.open,
                            Symbol = symbol,
                            Volume = volume,
                            OpenPrice = result.Price,
                            Type = actualOrderType.ToString()
                        });

                        this.ShowMsg($"【高级开仓成功】主订单:{tradeInfo.order}, 从订单:{result.Order}, " +
                                    $"成交价:{result.Price:F5}, 止损:{request.Sl:F5}, 止盈:{request.Tp:F5}",
                                    LogEmuns.Success);
                        return result.Order;
                    }
                    else
                    {
                        this.ShowMsg($"【高级开仓失败】错误码:{result.Retcode}, " +
                                    $"错误信息:{GetErrorDescription(result.Retcode)}",
                                    LogEmuns.Error);
                    }
                }
                else
                {
                    // 获取详细错误信息
                    int lastError = mtClient.GetLastError();
                    string errorDesc = GetMT5ErrorDescription(lastError);
                    this.ShowMsg($"【高级开仓失败】OrderSend返回false, MT5错误码:{lastError}, 描述:{errorDesc}", LogEmuns.Error);

                    // 记录请求参数用于调试
                    this.ShowMsg($"  请求参数 - 品种:{request.Symbol}, 方向:{request.Type}, 手数:{request.Volume}, " +
                                $"价格:{request.Price}, 止损:{request.Sl}, 止盈:{request.Tp}", LogEmuns.Debug);
                }

                retryCount++;
                if (retryCount < 3)
                {
                    this.ShowMsg($"开始第{retryCount}次重试...", LogEmuns.Warn);
                    Thread.Sleep(200 * retryCount); // 递增延迟
                }
            }

            this.ShowMsg($"【高级开仓失败】主订单:{tradeInfo.order}, 重试3次都失败，请人工接入",
                        LogEmuns.Error);
            return 0;
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【高级开仓异常】{ex.Message}", LogEmuns.Error, ex);
            return 0;
        }
    }

    /// <summary>
    /// 获取错误代码描述
    /// </summary>
    private string GetErrorDescription(uint retcode)
    {
        switch (retcode)
        {
            case 10004: return "请求被拒绝";
            case 10006: return "请求被拒绝";
            case 10007: return "请求被市场取消";
            case 10010: return "只能部分执行";
            case 10011: return "请求处理错误";
            case 10012: return "请求超时取消";
            case 10013: return "无效请求";
            case 10014: return "无效交易量";
            case 10015: return "无效价格";
            case 10016: return "无效止损";
            case 10017: return "交易被禁用";
            case 10018: return "市场关闭";
            case 10019: return "资金不足";
            case 10020: return "价格改变";
            case 10021: return "没有报价";
            case 10022: return "无效订单有效期";
            case 10023: return "订单状态改变";
            case 10025: return "无变化";
            case 10026: return "自动交易被服务器禁用";
            case 10027: return "自动交易被客户端禁用";
            case 10028: return "请求被锁定处理";
            case 10029: return "订单或仓位被冻结";
            case 10030: return "无效的订单填充类型";
            case 10031: return "无连接";
            default: return $"未知错误({retcode})";
        }
    }

    /// <summary>
    /// 获取MT5错误描述
    /// </summary>
    private string GetMT5ErrorDescription(int errorCode)
    {
        switch (errorCode)
        {
            case 0: return "无错误";
            case 4001: return "错误的函数指针";
            case 4002: return "数组索引超出范围";
            case 4003: return "无法为函数调用分配内存";
            case 4004: return "递归堆栈溢出";
            case 4005: return "堆栈中没有内存用于参数";
            case 4006: return "无内存用于字符串参数";
            case 4007: return "无内存用于临时字符串";
            case 4008: return "未初始化的字符串";
            case 4009: return "字符串中未初始化的数组";
            case 4010: return "没有内存用于数组";
            case 4011: return "数组太长";
            case 4012: return "除零余数";
            case 4013: return "零除";
            case 4014: return "未知命令";
            case 4015: return "错误的跳转";
            case 4016: return "未初始化的数组";
            case 4017: return "DLL调用不允许";
            case 4018: return "无法加载库";
            case 4019: return "无法调用函数";
            case 4020: return "Expert函数调用不允许";
            case 4021: return "没有足够的内存从函数返回字符串";
            case 4022: return "系统忙";
            case 4050: return "无效的函数参数计数";
            case 4051: return "无效的函数参数值";
            case 4052: return "字符串函数内部错误";
            case 4053: return "某些数组错误";
            case 4054: return "不正确的序列数组使用";
            case 4055: return "自定义指标错误";
            case 4056: return "数组不兼容";
            case 4057: return "全局变量处理错误";
            case 4058: return "找不到全局变量";
            case 4059: return "在测试模式下不允许函数";
            case 4060: return "函数未确认";
            case 4061: return "发送邮件错误";
            case 4062: return "期望字符串参数";
            case 4063: return "期望整数参数";
            case 4064: return "期望双精度参数";
            case 4065: return "期望数组作为参数";
            case 4066: return "请求的历史数据处于更新状态";
            case 4067: return "交易函数中出现内部错误";
            case 4068: return "未找到资源";
            case 4069: return "不支持资源";
            case 4070: return "资源名称重复";
            case 4071: return "无法初始化自定义指标";
            case 4072: return "无法加载自定义指标";
            case 4073: return "没有历史数据";
            case 4074: return "没有足够的内存用于历史数据";
            case 4075: return "市场关闭";
            case 4099: return "文件结束";
            case 4100: return "文件错误";
            case 4101: return "错误的文件名";
            case 4102: return "打开的文件太多";
            case 4103: return "无法打开文件";
            case 4104: return "不兼容的文件访问模式";
            case 4105: return "没有选择订单";
            case 4106: return "未知品种";
            case 4107: return "无效价格参数用于交易功能";
            case 4108: return "无效订单号";
            case 4109: return "不允许交易";
            case 4110: return "不允许多头";
            case 4111: return "不允许空头";
            case 4112: return "自动交易被专家停止";
            case 4200: return "对象已存在";
            case 4201: return "请求未知对象属性";
            case 4202: return "对象不存在";
            case 4203: return "未知对象类型";
            case 4204: return "没有对象名称";
            case 4205: return "对象坐标错误";
            case 4206: return "未找到指定子窗口";
            case 4207: return "使用对象时出错";
            case 4756: return "交易请求被拒绝 - 可能是止损/止盈距离不符合要求或参数无效";
            case 4757: return "订单过期";
            case 4758: return "订单状态已更改";
            case 4759: return "剩余量太小";
            case 4760: return "持仓量不足";
            default: return $"未知MT5错误代码:{errorCode}";
        }
    }

    private void btnTest_Click(object sender, EventArgs e)
    {
        // 运行调试连接测试
        Task.Run(() =>
        {
            try
            {
                this.ShowMsg("========== 开始调试连接问题 ==========");

                // 重定向控制台输出到日志窗口
                var originalOut = Console.Out;
                var writer = new System.IO.StringWriter();
                Console.SetOut(writer);

                // 首先检查DLL加载
                // DebugConnection.CheckDllLoading();

                // 然后运行连接调试
                // DebugConnection.TestConnection();

                // 获取测试结果并显示
                string testOutput = writer.ToString();
                Console.SetOut(originalOut);

                // 将测试结果按行显示在日志窗口
                foreach (var line in testOutput.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                {
                    this.ShowMsg(line);
                }

                this.ShowMsg("========== 调试完成 ==========");

                // 显示当前MtClientMain的状态
                this.ShowMsg($"\n当前主账号客户端状态:");
                this.ShowMsg($"  MtClientMain是否为null: {(this.MtClientMain == null ? "是" : "否")}");
                if (this.MtClientMain != null)
                {
                    this.ShowMsg($"  MtClientMain连接状态: {this.MtClientMain.ConnectionState}");
                }
            }
            catch (Exception ex)
            {
                this.ShowMsg($"调试异常: {ex.Message}", LogEmuns.Error, ex);
            }
        });
    }

    public static T GetControlPropertyThreadSafe<T>(Control control, Func<ComboBox, T> getter)
    {
        ComboBox cmb = control as ComboBox;
        if (cmb == null)
            throw new ArgumentException("控件不是 ComboBox 类型");
        if (!cmb.InvokeRequired)
            return getter(cmb);
        T result = default(T);
        cmb.Invoke((Action)(() => result = getter(cmb)));
        return result;
    }

    /// <summary>
    /// 获取账户余额
    /// </summary>
    /// <param name="mtClient">MT5客户端</param>
    /// <returns>账户余额</returns>
    private double GetAccountBalance(MtApi5Client mtClient)
    {
        // 注意：实际的MT5账户余额获取需要根据MtApi5的具体API实现
        // 目前使用保守的默认值，确保Kelly计算的安全性
        try
        {
            // TODO: 在MtApi5 API文档确认后，使用正确的方法获取账户余额
            // 可能的方法名：AccountBalance(), GetAccountBalance(), Balance等
            this.ShowMsg("【账户余额】使用保守默认余额进行Kelly计算", LogEmuns.Debug);
            return 10000.0; // 保守的默认资金基准，适用于大多数交易场景
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【账户余额】获取失败: {ex.Message}，使用保守默认值", LogEmuns.Warn, ex);
            return 10000.0; // 异常时使用保守的默认值
        }
    }

    /// <summary>
    /// 获取交易品种的当前价格基准
    /// </summary>
    /// <param name="symbol">交易品种</param>
    /// <param name="mtClient">MT5客户端</param>
    /// <returns>价格基准</returns>
    private double GetSymbolPriceBase(string symbol, MtApi5Client mtClient)
    {
        // 注意：实际的MT5价格获取需要根据MtApi5的具体API实现
        // 目前根据交易品种使用合理的价格基准，确保Kelly计算的准确性
        try
        {
            // TODO: 在MtApi5 API文档确认后，使用正确的方法获取实时报价
            // 可能的方法名：Quote(), GetTick(), GetPrice()等
            
            // 根据品种类型使用合理的默认价格基准
            string upperSymbol = symbol?.ToUpper() ?? "";
            
            if (upperSymbol.Contains("JPY"))
                return 110.0; // 日元对基准价格
            else if (upperSymbol.Contains("XAU") || upperSymbol.Contains("GOLD"))
                return 2000.0; // 黄金基准价格  
            else if (upperSymbol.Contains("BTC") || upperSymbol.Contains("BITCOIN"))
                return 50000.0; // 比特币基准价格
            else if (upperSymbol.Contains("EUR") || upperSymbol.Contains("GBP") || upperSymbol.Contains("USD"))
                return 1.2; // 主要货币对基准价格
            else
                return 100.0; // 通用基准价格
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【价格基准】获取{symbol}价格失败: {ex.Message}，使用默认基准", LogEmuns.Debug, ex);
            return 100.0; // 异常时使用通用基准价格
        }
    }

    /// <summary>
    /// 设置Kelly优化参数
    /// </summary>
    /// <param name="enabled">是否启用Kelly优化</param>
    /// <param name="safetyFactor">安全系数（0.1-0.5）</param>
    /// <param name="maxPosition">最大仓位限制</param>
    /// <param name="minPosition">最小仓位限制</param>
    public void ConfigureKellyOptimization(bool enabled = true, double safetyFactor = 0.25, 
        double maxPosition = 10.0, double minPosition = 0.01)
    {
        this.enableKellyOptimization = enabled;
        this.kellySafetyFactor = Math.Max(0.1, Math.Min(0.5, safetyFactor));
        this.maxPositionSize = Math.Max(0.01, maxPosition);
        this.minPositionSize = Math.Max(0.01, Math.Min(minPosition, maxPosition));
        
        this.ShowMsg($"【Kelly配置】启用:{enabled}, 安全系数:{this.kellySafetyFactor:F2}, " +
                    $"仓位范围:[{this.minPositionSize:F2}, {this.maxPositionSize:F2}]", 
                    LogEmuns.Success);
    }

    /// <summary>
    /// 获取当前Kelly优化状态信息
    /// </summary>
    /// <returns>Kelly状态信息字符串</returns>
    public string GetKellyOptimizationStatus()
    {
        return $"Kelly优化: {(enableKellyOptimization ? "启用" : "禁用")}, " +
               $"安全系数: {kellySafetyFactor:F2}, " +
               $"仓位范围: [{minPositionSize:F2}, {maxPositionSize:F2}], " +
               $"计算模式: {positionMode}";
    }

    /// <summary>
    /// 动态调整杠杆比例
    /// 基于市场波动率和破产概率模型计算最优杠杆
    /// </summary>
    /// <param name="marketVolatilityOverride">市场波动率覆盖值（可选）</param>
    /// <returns>调整后的杠杆比例</returns>
    public double AdjustLeverageRatio(double? marketVolatilityOverride = null)
    {
        try
        {
            if (!enableLeverageOptimization)
            {
                this.ShowMsg("【杠杆优化】功能已禁用，保持当前杠杆", LogEmuns.Debug);
                return currentLeverageRatio;
            }
            
            // 使用提供的波动率或默认值
            double volatility = marketVolatilityOverride ?? marketVolatility;
            
            // 获取当前账户资金（使用主客户端）
            double accountCapital = GetAccountBalance(MtClientMain);
            
            // 使用LeverageController进行杠杆控制
            var controlResult = leverageController.ControlLeverage(
                expectedMarketReturn, volatility, accountCapital);
            
            // 更新当前杠杆比例
            currentLeverageRatio = controlResult.RecommendedLeverage;
            
            // 记录控制结果
            this.ShowMsg($"【杠杆控制】{controlResult.ControlReason}, " +
                        $"破产概率:{controlResult.CurrentBankruptcyProbability:P2}, " +
                        $"风险等级:{controlResult.RiskLevel}, " +
                        $"新杠杆:{controlResult.RecommendedLeverage:F1}倍", LogEmuns.Success);
            
            // 显示预警信息
            foreach (var warning in controlResult.Warnings)
            {
                this.ShowMsg($"【杠杆预警】{warning}", LogEmuns.Warn);
            }
            
            // 如果需要立即降杠杆
            if (controlResult.RequiresImmediateReduction)
            {
                this.ShowMsg($"【紧急操作】破产概率过高，已执行紧急降杠杆", LogEmuns.Error);
            }
            
            return currentLeverageRatio;
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【杠杆优化】计算异常: {ex.Message}，保持当前杠杆", LogEmuns.Error, ex);
            return currentLeverageRatio;
        }
    }
    
    /// <summary>
    /// 更新市场环境参数
    /// </summary>
    /// <param name="newExpectedReturn">新的期望收益率</param>
    /// <param name="newVolatility">新的市场波动率</param>
    public void UpdateMarketEnvironment(double newExpectedReturn, double newVolatility)
    {
        this.expectedMarketReturn = newExpectedReturn;
        this.marketVolatility = newVolatility;
        
        this.ShowMsg($"【市场环境】更新参数 - 期望收益:{newExpectedReturn:F4}, 波动率:{newVolatility:F4}", 
                    LogEmuns.Debug);
        
        // 自动调整杠杆比例
        if (enableLeverageOptimization)
        {
            AdjustLeverageRatio();
        }
    }
    
    /// <summary>
    /// 配置杠杆优化参数
    /// </summary>
    /// <param name="enabled">是否启用杠杆优化</param>
    /// <param name="maxBankruptcyProb">最大破产概率阈值</param>
    /// <param name="expectedReturn">预期市场收益率</param>
    /// <param name="volatility">市场波动率</param>
    public void ConfigureLeverageOptimization(bool enabled = true, 
        double maxBankruptcyProb = 0.05, double expectedReturn = 0.001, double volatility = 0.015)
    {
        this.enableLeverageOptimization = enabled;
        this.maxBankruptcyProbability = Math.Max(0.001, Math.Min(0.1, maxBankruptcyProb));
        this.expectedMarketReturn = expectedReturn;
        this.marketVolatility = Math.Max(0.001, volatility);
        
        this.ShowMsg($"【杠杆配置】启用:{enabled}, 破产概率阈值:{this.maxBankruptcyProbability:P2}, " +
                    $"期望收益:{this.expectedMarketReturn:F4}, 波动率:{this.marketVolatility:F4}", 
                    LogEmuns.Success);
        
        // 应用新配置
        if (enabled)
        {
            AdjustLeverageRatio();
        }
    }
    
    /// <summary>
    /// 获取当前杠杆优化状态信息
    /// </summary>
    /// <returns>杠杆状态信息字符串</returns>
    public string GetLeverageOptimizationStatus()
    {
        if (!enableLeverageOptimization)
        {
            return "杠杆优化: 禁用";
        }
        
        try
        {
            // 获取LeverageController状态信息
            string controllerStatus = leverageController.GetControllerStatus();
            
            // 获取监控报告
            double accountCapital = GetAccountBalance(MtClientMain);
            var monitoringReport = leverageController.MonitorLeverageRisk(
                expectedMarketReturn, marketVolatility, accountCapital);
            
            return $"杠杆优化: 启用, {controllerStatus}, " +
                   $"破产概率: {monitoringReport.BankruptcyProbability:P2}, " +
                   $"安全边际: {monitoringReport.SafetyMargin:P2}, " +
                   $"监控状态: {monitoringReport.Status}, " +
                   $"风险等级: {monitoringReport.RiskLevel}";
        }
        catch (Exception ex)
        {
            return $"杠杆优化: 启用, 状态查询异常: {ex.Message}";
        }
    }
    
    /// <summary>
    /// 基于波动率环境智能调整杠杆
    /// 在交易前调用此方法以确保杠杆设置合理
    /// </summary>
    /// <param name="symbolVolatility">特定交易品种的波动率</param>
    /// <returns>建议的杠杆比例</returns>
    public double GetIntelligentLeverage(double symbolVolatility)
    {
        try
        {
            if (!enableLeverageOptimization)
            {
                return currentLeverageRatio;
            }
            
            // 计算该品种的最优杠杆
            double optimalLeverage = bankruptcyModel.CalculateOptimalLeverage(
                expectedMarketReturn, symbolVolatility);
            
            // 基于波动率环境调整
            double environmentAdjustedLeverage = bankruptcyModel.AdjustLeverageByVolatilityEnvironment(
                symbolVolatility, optimalLeverage);
            
            // 应用破产概率约束
            double safetyConstrainedLeverage = bankruptcyModel.CalculateLeverageLimit(
                expectedMarketReturn, symbolVolatility, maxBankruptcyProbability);
            
            // 取最保守的杠杆设置
            double recommendedLeverage = Math.Min(environmentAdjustedLeverage, safetyConstrainedLeverage);
            
            this.ShowMsg($"【智能杠杆】品种波动率:{symbolVolatility:F4}, " +
                        $"最优杠杆:{optimalLeverage:F1}, 环境调整:{environmentAdjustedLeverage:F1}, " +
                        $"安全约束:{safetyConstrainedLeverage:F1}, 最终建议:{recommendedLeverage:F1}", 
                        LogEmuns.Debug);
            
            return Math.Round(recommendedLeverage, 1);
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【智能杠杆】计算异常: {ex.Message}，使用默认杠杆", LogEmuns.Warn, ex);
            return Math.Min(currentLeverageRatio, 50.0); // 异常时使用保守杠杆
        }
    }

    /// <summary>
    /// 开仓前杠杆安全检查
    /// 确保破产概率在5%以下才允许开仓
    /// </summary>
    /// <param name="proposedPositionSize">拟开仓位大小</param>
    /// <param name="symbolVolatility">品种波动率</param>
    /// <returns>检查结果：是否允许开仓以及建议的杠杆</returns>
    public (bool IsAllowed, double RecommendedLeverage, string Reason) ValidatePositionOpening(
        double proposedPositionSize, double symbolVolatility)
    {
        try
        {
            if (!enableLeverageOptimization)
            {
                return (true, currentLeverageRatio, "杠杆优化已禁用，使用当前杠杆");
            }

            // 获取账户资金
            double accountCapital = GetAccountBalance(MtClientMain);
            
            // 获取当前风险监控报告
            var monitoringReport = leverageController.MonitorLeverageRisk(
                expectedMarketReturn, symbolVolatility, accountCapital);

            // 检查当前破产概率是否超过5%阈值
            if (monitoringReport.BankruptcyProbability > LeverageController.TARGET_BANKRUPTCY_THRESHOLD)
            {
                // 执行紧急降杠杆
                double emergencyLeverage = leverageController.EmergencyLeverageReduction();
                currentLeverageRatio = emergencyLeverage;
                
                this.ShowMsg($"【安全防护】破产概率{monitoringReport.BankruptcyProbability:P2}超过5%阈值，" +
                           $"禁止开仓并执行紧急降杠杆至{emergencyLeverage:F1}倍", LogEmuns.Error);
                
                return (false, emergencyLeverage, 
                       $"破产概率{monitoringReport.BankruptcyProbability:P2}超过安全阈值，已执行紧急降杠杆");
            }

            // 检查是否接近预警阈值
            if (monitoringReport.BankruptcyProbability > LeverageController.WARNING_BANKRUPTCY_THRESHOLD)
            {
                this.ShowMsg($"【风险预警】破产概率{monitoringReport.BankruptcyProbability:P2}接近安全上限，" +
                           $"建议谨慎开仓", LogEmuns.Warn);
            }

            // 基于品种特性控制杠杆
            var controlResult = leverageController.ControlLeverage(
                expectedMarketReturn, symbolVolatility, accountCapital);

            // 更新当前杠杆
            currentLeverageRatio = controlResult.RecommendedLeverage;

            // 记录预警信息
            foreach (var warning in controlResult.Warnings)
            {
                this.ShowMsg($"【开仓检查】{warning}", LogEmuns.Warn);
            }

            string reason = $"破产概率{controlResult.CurrentBankruptcyProbability:P2}，" +
                          $"风险等级{controlResult.RiskLevel}，允许开仓";

            return (true, controlResult.RecommendedLeverage, reason);
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【开仓检查】安全检查异常: {ex.Message}，使用保守策略", LogEmuns.Error, ex);
            
            // 异常情况下使用最小杠杆
            double safeLeverage = LeverageController.MIN_LEVERAGE_LIMIT;
            return (true, safeLeverage, $"检查异常，使用最小安全杠杆{safeLeverage}倍");
        }
    }

    /// <summary>
    /// 杠杆控制器状态重置
    /// 在系统重启或参数重新配置时调用
    /// </summary>
    public void ResetLeverageController()
    {
        try
        {
            leverageController?.ResetController(currentLeverageRatio);
            this.ShowMsg($"【杠杆控制】控制器已重置，初始杠杆:{currentLeverageRatio:F1}倍", LogEmuns.Success);
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【杠杆控制】重置失败: {ex.Message}", LogEmuns.Error, ex);
        }
    }

    /// <summary>
    /// 优化的交易处理流程
    /// 集成所有优化组件，包括风险评估、仓位优化、时机判断、重试机制等
    /// </summary>
    /// <param name="tradeInfo">交易信息</param>
    /// <param name="mtClient">MT5客户端</param>
    /// <param name="isMain">是否为主账户</param>
    /// <returns>交易执行结果</returns>
    internal async Task<TradeExecutionResult> ProcessTradeOptimized(TradeInfo tradeInfo, MtApi5Client mtClient, bool isMain = true)
    {
        var result = new TradeExecutionResult();
        
        try
        {
            this.ShowMsg($"【优化交易】开始处理 - 订单号:{tradeInfo.order}, 品种:{tradeInfo.symbol}, 手数:{tradeInfo.volume}", LogEmuns.Info);
            
            // 步骤1：使用AdaptiveHedgeOptimizer进行统一参数优化
            var marketData = CreateMarketData(tradeInfo);
            var accountStatus = CreateAccountStatus(mtClient);

            var optimizedParams = await adaptiveHedgeOptimizer.OptimizeParametersAsync(marketData, accountStatus);

            this.ShowMsg($"【参数优化】仓位:{optimizedParams.PositionSize:F2}手, 杠杆:1:{optimizedParams.Leverage:F0}, " +
                        $"止损:{optimizedParams.StopLoss:P2}, 敞口:{optimizedParams.GapRatio:P2}, " +
                        $"市场状态:{optimizedParams.MarketCondition}, 置信度:{optimizedParams.ConfidenceScore:P1}", LogEmuns.Info);

            // 步骤2：风险评估 - 使用VaR和CVaR评估潜在风险
            var riskAssessment = await PerformRiskAssessment(tradeInfo, mtClient);
            if (!riskAssessment.IsAcceptable)
            {
                this.ShowMsg($"【风险拒绝】VaR:{riskAssessment.VaR:F4}, CVaR:{riskAssessment.CVaR:F4}, 超出风险阈值", LogEmuns.Error);
                result.Success = false;
                result.Reason = "风险评估未通过";
                return result;
            }

            // 步骤3：时机评估 - 使用GARCH模型预测波动率
            var timingAssessment = await PerformTimingAssessment(tradeInfo);
            if (!timingAssessment.IsOptimalTime)
            {
                this.ShowMsg($"【时机警告】当前波动率:{timingAssessment.CurrentVolatility:F4}, 预测波动率:{timingAssessment.PredictedVolatility:F4}, 建议等待", LogEmuns.Warn);
                // 注意：可以选择继续或等待，这里选择继续但调整仓位
                riskAssessment.PositionAdjustmentFactor = timingAssessment.RecommendedAdjustment;
            }

            // 步骤4：使用优化后的参数创建仓位信息
            var optimizedPosition = new OptimizedPositionResult
            {
                PositionSize = optimizedParams.PositionSize,
                RequiresHedging = optimizedParams.GapRatio > 0.01,
                HedgeRatio = optimizedParams.GapRatio
            };
            
            // 步骤5：杠杆验证 - 确保破产概率在安全范围内
            var leverageCheck = ValidatePositionOpening(optimizedPosition.PositionSize, timingAssessment.CurrentVolatility);
            if (!leverageCheck.IsAllowed)
            {
                this.ShowMsg($"【杠杆拒绝】{leverageCheck.Reason}", LogEmuns.Error);
                result.Success = false;
                result.Reason = leverageCheck.Reason;
                return result;
            }

            // 步骤6：对冲策略 - 如果需要，应用Gap对冲策略
            if (optimizedPosition.RequiresHedging)
            {
                await ApplyHedgingStrategy(tradeInfo, optimizedPosition);
            }

            // 步骤7：执行交易 - 使用Poisson重试机制和熔断器
            result = await ExecuteTradeWithRetry(tradeInfo, optimizedPosition, mtClient);

            // 步骤8：结果记录和分析
            await RecordAndAnalyzeResult(tradeInfo, result, riskAssessment, timingAssessment, optimizedPosition);

            // 步骤9：参数自动调优（如果启用）
            if (enableAutomaticParameterTuning && ShouldUpdateParameters())
            {
                await UpdateOptimizationParameters();
            }
            
            return result;
        }
        catch (Exception ex)
        {
            this.ShowMsg($"【优化交易】处理异常: {ex.Message}", LogEmuns.Error, ex);
            result.Success = false;
            result.Reason = $"处理异常: {ex.Message}";
            return result;
        }
    }
    
    /// <summary>
    /// 执行风险评估
    /// </summary>
    private async Task<RiskAssessmentResult> PerformRiskAssessment(TradeInfo tradeInfo, MtApi5Client mtClient)
    {
        return await Task.Run(() =>
        {
            var riskMetrics = serviceProvider.GetRequiredService<RiskMetrics>();
            
            // 获取历史数据
            var historicalData = GetHistoricalReturns(tradeInfo.symbol);
            
            // 计算VaR和CVaR
            double confidence = 0.95;
            double positionValue = tradeInfo.volume * 10000; // 假设每手10000单位
            double var = riskMetrics.CalculateParametricVaR(confidence, positionValue);
            double cvar = riskMetrics.CalculateCVaR(confidence, positionValue);

            // 计算风险调整后的夏普比率
            double riskFreeRate = 0.02 / 252; // 日化无风险利率
            double sharpeRatio = riskMetrics.CalculateSharpeRatio(historicalData.ToList(), riskFreeRate);
            
            // 判断风险是否可接受
            bool isAcceptable = var > -0.05 && cvar > -0.10 && sharpeRatio > 0.5;
            
            this.ShowMsg($"【风险评估】VaR(95%):{var:F4}, CVaR(95%):{cvar:F4}, Sharpe:{sharpeRatio:F2}, 评估:{(isAcceptable ? "通过" : "拒绝")}", LogEmuns.Info);
            
            return new RiskAssessmentResult
            {
                VaR = var,
                CVaR = cvar,
                SharpeRatio = sharpeRatio,
                IsAcceptable = isAcceptable,
                PositionAdjustmentFactor = 1.0
            };
        });
    }
    
    /// <summary>
    /// 执行时机评估
    /// </summary>
    private async Task<TimingAssessmentResult> PerformTimingAssessment(TradeInfo tradeInfo)
    {
        return await Task.Run(() =>
        {
            var garchModel = serviceProvider.GetRequiredService<GarchModel>();
            
            // 获取历史收益率数据
            var returns = GetHistoricalReturns(tradeInfo.symbol);
            
            // 使用GARCH模型预测波动率
            // 先计算当前条件方差
            var returnsArray = returns.ToArray();
            var conditionalVariances = garchModel.CalculateConditionalVariances(
                returnsArray, garchModel.Omega, garchModel.Alpha, garchModel.Beta, garchModel.Mu);
            double currentVariance = conditionalVariances[conditionalVariances.Length - 1];

            // 预测下一期波动率
            double predictedVolatility = garchModel.PredictNextVolatility(currentVariance);
            double currentVolatility = garchModel.GetCurrentVolatility(returnsArray);
            
            // 检测波动率聚类
            var clusteringResult = garchModel.DetectVolatilityClustering(returns);
            
            // 判断是否为最优时机
            bool isOptimal = predictedVolatility < currentVolatility * 1.2 && 
                           clusteringResult.CurrentState != VolatilityState.High;
            
            // 计算仓位调整因子
            double adjustment = 1.0;
            if (clusteringResult.CurrentState == VolatilityState.High)
            {
                adjustment = 0.5; // 高波动时减半仓位
            }
            else if (clusteringResult.CurrentState == VolatilityState.Medium)
            {
                adjustment = 0.75; // 中等波动时减少25%
            }
            
            this.ShowMsg($"【时机评估】当前波动:{currentVolatility:F4}, 预测波动:{predictedVolatility:F4}, " +
                        $"状态:{clusteringResult.CurrentState}, 调整系数:{adjustment:F2}", LogEmuns.Info);
            
            return new TimingAssessmentResult
            {
                CurrentVolatility = currentVolatility,
                PredictedVolatility = predictedVolatility,
                IsOptimalTime = isOptimal,
                RecommendedAdjustment = adjustment,
                VolatilityState = clusteringResult.CurrentState
            };
        });
    }
    
    /// <summary>
    /// 优化仓位大小
    /// </summary>
    private async Task<OptimizedPositionResult> OptimizePosition(TradeInfo tradeInfo, RiskAssessmentResult risk, TimingAssessmentResult timing)
    {
        return await Task.Run(() =>
        {
            // 基础仓位计算
            double basePosition = tradeInfo.volume;
            
            // 使用Kelly公式计算
            double kellyPosition = CalculateKellyOptimizedPosition(tradeInfo, basePosition, MtClientFollow);
            
            // 应用风险和时机调整
            double adjustedPosition = kellyPosition * risk.PositionAdjustmentFactor * timing.RecommendedAdjustment;
            
            // 如果启用NSGA-II多目标优化
            if (enableNSGA2Optimization)
            {
                var nsga2Result = nsga2Optimizer.Optimize(
                    adjustedPosition,
                    risk.SharpeRatio,
                    timing.CurrentVolatility,
                    nsga2PopulationSize,
                    nsga2MaxGenerations
                );
                
                // 选择Pareto前沿中最平衡的解
                var optimalSolution = nsga2Result.ParetoFront
                    .OrderByDescending(s => s.Objectives[0] - s.Objectives[1]) // 平衡收益和风险
                    .FirstOrDefault();
                
                if (optimalSolution != null)
                {
                    adjustedPosition = optimalSolution.Variables[0]; // 仓位大小
                    this.ShowMsg($"【NSGA-II优化】最优仓位:{adjustedPosition:F4}, 目标值:[{string.Join(", ", optimalSolution.Objectives.Select(o => o.ToString("F4")))}]", LogEmuns.Success);
                }
            }
            
            // 应用仓位限制
            double finalPosition = Math.Max(minPositionSize, Math.Min(maxPositionSize, Math.Round(adjustedPosition, 2)));
            
            // 判断是否需要对冲
            bool requiresHedging = timing.CurrentVolatility > 0.03 || risk.CVaR < -0.08;
            
            this.ShowMsg($"【仓位优化】基础:{basePosition:F2}, Kelly:{kellyPosition:F2}, 最终:{finalPosition:F2}, 需要对冲:{requiresHedging}", LogEmuns.Info);
            
            return new OptimizedPositionResult
            {
                PositionSize = finalPosition,
                RequiresHedging = requiresHedging,
                HedgeRatio = requiresHedging ? 0.3 : 0.0
            };
        });
    }
    
    /// <summary>
    /// 应用对冲策略
    /// </summary>
    private async Task ApplyHedgingStrategy(TradeInfo tradeInfo, OptimizedPositionResult position)
    {
        await Task.Run(() =>
        {
            var gapHedging = serviceProvider.GetRequiredService<GapHedgingStrategy>();
            var betaCalculator = serviceProvider.GetRequiredService<BetaCalculator>();
            var dynamicAdjuster = serviceProvider.GetRequiredService<DynamicHedgeAdjuster>();
            
            // 计算Beta值
            var marketReturns = GetHistoricalReturns("SPX500"); // 使用市场指数
            var assetReturns = GetHistoricalReturns(tradeInfo.symbol);
            var betaResult = betaCalculator.Calculate(GetHistoricalPrices(tradeInfo.symbol), GetMarketPrices(), 20);
            double beta = betaResult.Beta;
            
            // 识别Gap类型
            var prices = GetHistoricalPrices(tradeInfo.symbol);
            // 获取最新的价格数据用于缺口识别
            double prevClose = prices.Length > 1 ? prices[prices.Length - 2] : prices[0];
            double currentOpen = prices.Length > 0 ? prices[prices.Length - 1] : 0;
            double currentHigh = currentOpen * 1.01; // 暂时使用模拟值
            double currentLow = currentOpen * 0.99;  // 暂时使用模拟值
            double prevVolume = 10000;  // 暂时使用模拟值
            double currentVolume = 12000; // 暂时使用模拟值

            var gapData = gapHedging.IdentifyGap(
                prevClose, currentOpen, currentHigh,
                currentLow, prevVolume, currentVolume);
            var gapType = gapData.Type;
            
            // 计算对冲比例
            var hedgeResult = gapHedging.CalculateDeltaNeutralHedge(
                gapData,  // 传入完整的gap数据
                beta,
                GetCurrentPrice(tradeInfo.symbol),
                GetCurrentPrice("SPX500")
            );
            
            // 动态调整对冲
            var adjustment = dynamicAdjuster.AdjustForVolatility(
                hedgeResult.HedgeRatio,
                GetCurrentVolatility(tradeInfo.symbol)
            );
            
            this.ShowMsg($"【对冲策略】Beta:{beta:F2}, Gap类型:{gapType}, 对冲比例:{hedgeResult.HedgeRatio:F2}, 调整后:{adjustment.NewHedgeRatio:F2}", LogEmuns.Info);

            // 记录对冲策略（实际执行需要根据具体需求实现）
            position.HedgeRatio = adjustment.NewHedgeRatio;
        });
    }
    
    /// <summary>
    /// 使用重试机制执行交易
    /// </summary>
    private async Task<TradeExecutionResult> ExecuteTradeWithRetry(TradeInfo tradeInfo, OptimizedPositionResult position, MtApi5Client mtClient)
    {
        return await Task.Run(async () =>
        {
            var retryExecutor = serviceProvider.GetRequiredService<PoissonRetryExecutor>();
            var circuitBreaker = serviceProvider.GetRequiredService<CircuitBreaker>();
            
            var result = new TradeExecutionResult();
            
            // 使用熔断器包装执行
            try
            {
                var executeResult = await circuitBreaker.ExecuteWithCircuitBreakerAsync(async () =>
                {
                    // 使用Poisson重试执行器
                    return await retryExecutor.ExecuteWithRetryAsync<(bool, ulong)>(async () =>
                    {
                        MqlTradeResult tradeResult = null;
                        bool success = false;
                        
                        // 执行交易
                        if (tradeInfo.direction == ENUM_ORDER_TYPE.ORDER_TYPE_BUY)
                        {
                            success = mtClient.Buy(out tradeResult, position.PositionSize, tradeInfo.symbol);
                        }
                        else
                        {
                            success = mtClient.Sell(out tradeResult, position.PositionSize, tradeInfo.symbol);
                        }
                        
                        if (success && tradeResult != null)
                        {
                            return (true, tradeResult.Order);
                        }
                        
                        throw new Exception($"交易执行失败，错误码: {tradeResult?.Retcode}");
                    },
                    operationName: "TradeExecution",
                    maxRetries: 3);
                });
                
                result.Success = executeResult.Item1;
                result.OrderId = executeResult.Item2;
                result.ExecutedPosition = position.PositionSize;
                
                this.ShowMsg($"【交易执行】成功 - 订单号:{result.OrderId}, 仓位:{result.ExecutedPosition:F2}", LogEmuns.Success);
            }
            catch (CircuitBreakerOpenException)
            {
                this.ShowMsg("【熔断器】熔断器已打开，拒绝执行交易", LogEmuns.Error);
                result.Success = false;
                result.Reason = "熔断器打开";
            }
            catch (Exception ex)
            {
                this.ShowMsg($"【交易执行】执行失败: {ex.Message}", LogEmuns.Error, ex);
                result.Success = false;
                result.Reason = ex.Message;
            }
            
            return result;
        });
    }
    
    /// <summary>
    /// 记录和分析交易结果
    /// </summary>
    private async Task RecordAndAnalyzeResult(TradeInfo tradeInfo, TradeExecutionResult result, 
        RiskAssessmentResult risk, TimingAssessmentResult timing, OptimizedPositionResult position)
    {
        await Task.Run(() =>
        {
            // 创建交易记录
            var tradeRecord = new OptimizedTradeRecord
            {
                Timestamp = DateTime.Now,
                Symbol = tradeInfo.symbol,
                Direction = tradeInfo.direction.ToString(),
                RequestedVolume = tradeInfo.volume,
                ExecutedVolume = position.PositionSize,
                Success = result.Success,
                OrderId = result.OrderId,
                VaR = risk.VaR,
                CVaR = risk.CVaR,
                SharpeRatio = risk.SharpeRatio,
                CurrentVolatility = timing.CurrentVolatility,
                PredictedVolatility = timing.PredictedVolatility,
                HedgeRatio = position.HedgeRatio,
                FailureReason = result.Reason
            };
            
            // 保存到文件
            string recordPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "optimized_trades.json");
            var records = JsonFileHelper.ReadFromFile<List<OptimizedTradeRecord>>(recordPath) ?? new List<OptimizedTradeRecord>();
            records.Add(tradeRecord);
            JsonFileHelper.WriteToFile(recordPath, records);
            
            // 更新历史分析器
            if (result.Success)
            {
                var trade = new TradeModel
                {
                    m_ticket = tradeInfo.order,
                    f_ticket = result.OrderId,
                    Symbol = tradeInfo.symbol,
                    Time = DateTime.Now,
                    m_status = TradeStatus.open,
                    f_status = TradeStatus.open
                };
                trades.Add(trade);
            }
            
            this.ShowMsg($"【结果记录】交易记录已保存 - 成功:{result.Success}, VaR:{risk.VaR:F4}, 波动率:{timing.CurrentVolatility:F4}", LogEmuns.Info);
        });
    }
    
    /// <summary>
    /// 判断是否需要更新优化参数
    /// </summary>
    private bool ShouldUpdateParameters()
    {
        var timeSinceLastUpdate = DateTime.Now - lastOptimizationTime;
        return timeSinceLastUpdate.TotalMinutes >= optimizationUpdateIntervalMinutes;
    }
    
    /// <summary>
    /// 更新优化参数
    /// </summary>
    private async Task UpdateOptimizationParameters()
    {
        await Task.Run(() =>
        {
            this.ShowMsg("【参数优化】开始自动调优...", LogEmuns.Info);
            
            // 获取最近的交易记录
            string recordPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "optimized_trades.json");
            var records = JsonFileHelper.ReadFromFile<List<OptimizedTradeRecord>>(recordPath) ?? new List<OptimizedTradeRecord>();
            
            if (records.Count < 50)
            {
                this.ShowMsg("【参数优化】历史记录不足，跳过优化", LogEmuns.Debug);
                return;
            }
            
            // 计算性能指标
            var successRate = records.Count(r => r.Success) / (double)records.Count;
            var avgSharpe = records.Average(r => r.SharpeRatio);
            var avgVolatility = records.Average(r => r.CurrentVolatility);
            
            // 调整Kelly安全系数
            if (successRate < 0.6 && kellySafetyFactor < 0.4)
            {
                kellySafetyFactor = Math.Min(0.5, kellySafetyFactor * 1.1);
                this.ShowMsg($"【参数优化】提高Kelly安全系数至{kellySafetyFactor:F2}", LogEmuns.Info);
            }
            else if (successRate > 0.8 && kellySafetyFactor > 0.15)
            {
                kellySafetyFactor = Math.Max(0.1, kellySafetyFactor * 0.9);
                this.ShowMsg($"【参数优化】降低Kelly安全系数至{kellySafetyFactor:F2}", LogEmuns.Info);
            }
            
            // 调整最大破产概率阈值
            if (avgVolatility > 0.03)
            {
                maxBankruptcyProbability = Math.Max(0.03, maxBankruptcyProbability * 0.9);
                this.ShowMsg($"【参数优化】降低破产概率阈值至{maxBankruptcyProbability:P2}", LogEmuns.Info);
            }
            
            lastOptimizationTime = DateTime.Now;
            this.ShowMsg("【参数优化】自动调优完成", LogEmuns.Success);
        });
    }
    
    // 辅助方法
    private double[] GetHistoricalReturns(string symbol)
    {
        var symbolTrades = trades.Where(t => 
            t.Symbol?.ToUpper() == symbol?.ToUpper() && 
            t.CloseTime > DateTime.Now.AddDays(-30)
        ).ToList();
        
        if (symbolTrades.Count < 10)
        {
            // 返回模拟数据
            var random = serviceProvider.GetRequiredService<IRandomProvider>();
            return Enumerable.Range(0, 100).Select(_ => random.NextGaussian(0.001, 0.02)).ToArray();
        }
        
        // 计算实际收益率
        return symbolTrades.Select(t => t.Profit / Math.Max(1, t.OpenPrice)).ToArray();
    }
    
    private double[] GetHistoricalPrices(string symbol)
    {
        // 模拟历史价格数据
        var random = serviceProvider.GetRequiredService<IRandomProvider>();
        double basePrice = GetSymbolPriceBase(symbol, MtClientFollow);
        return Enumerable.Range(0, 100).Select(i => 
            basePrice * (1 + random.NextGaussian(0, 0.01))
        ).ToArray();
    }
    
    private double GetCurrentPrice(string symbol)
    {
        return GetSymbolPriceBase(symbol, MtClientFollow);
    }
    
    private double GetCurrentVolatility(string symbol)
    {
        var returns = GetHistoricalReturns(symbol);
        return returns.Length > 0 ? returns.Select(r => Math.Abs(r)).Average() : 0.02;
    }
    
    private double[] GetMarketPrices()
    {
        // 返回市场指数价格数据，这里返回模拟数据
        var prices = new double[100];
        var random = new DeterministicRandomProvider(42);
        prices[0] = 100;
        for (int i = 1; i < prices.Length; i++)
        {
            prices[i] = prices[i - 1] * (1 + (random.NextDouble() - 0.5) * 0.02);
        }
        return prices;
    }
    
    private double CalculateSharpeRatio(List<double> returns)
    {
        if (returns == null || returns.Count < 2) return 0;
        
        double avgReturn = returns.Average();
        double stdDev = Math.Sqrt(returns.Select(r => Math.Pow(r - avgReturn, 2)).Average());
        double riskFreeRate = 0.02 / 252; // 日化无风险利率
        
        if (stdDev == 0) return 0;
        return (avgReturn - riskFreeRate) / stdDev;
    }

    // 数据模型定义
    public class TradeExecutionResult
    {
        public bool Success { get; set; }
        public ulong OrderId { get; set; }
        public double ExecutedPosition { get; set; }
        public string Reason { get; set; }
    }
    
    public class RiskAssessmentResult
    {
        public double VaR { get; set; }
        public double CVaR { get; set; }
        public double SharpeRatio { get; set; }
        public bool IsAcceptable { get; set; }
        public double PositionAdjustmentFactor { get; set; }
    }
    
    public class TimingAssessmentResult
    {
        public double CurrentVolatility { get; set; }
        public double PredictedVolatility { get; set; }
        public bool IsOptimalTime { get; set; }
        public double RecommendedAdjustment { get; set; }
        public VolatilityState VolatilityState { get; set; }
    }
    
    public class OptimizedPositionResult
    {
        public double PositionSize { get; set; }
        public bool RequiresHedging { get; set; }
        public double HedgeRatio { get; set; }
    }
    
    public class OptimizedTradeRecord
    {
        public DateTime Timestamp { get; set; }
        public string Symbol { get; set; }
        public string Direction { get; set; }
        public double RequestedVolume { get; set; }
        public double ExecutedVolume { get; set; }
        public bool Success { get; set; }
        public ulong OrderId { get; set; }
        public double VaR { get; set; }
        public double CVaR { get; set; }
        public double SharpeRatio { get; set; }
        public double CurrentVolatility { get; set; }
        public double PredictedVolatility { get; set; }
        public double HedgeRatio { get; set; }
        public string FailureReason { get; set; }
    }

    /// <summary>
    /// 创建市场数据对象用于AdaptiveHedgeOptimizer
    /// </summary>
    private AdaptiveHedgeOptimizer.MarketData CreateMarketData(TradeInfo tradeInfo)
    {
        var marketData = new AdaptiveHedgeOptimizer.MarketData
        {
            Symbol = tradeInfo.symbol,
            Timestamp = DateTime.Now
        };

        // 获取历史价格和收益率数据
        var symbolTrades = this.trades.Where(t =>
            t.Symbol?.ToUpper() == tradeInfo.symbol?.ToUpper() &&
            t.CloseTime > DateTime.Now.AddDays(-historicalAnalysisWindow)
        ).ToList();

        var prices = new List<double>();
        var returns = new List<double>();

        // 模拟价格数据（实际应从MT5获取）
        if (MtClientMain.ConnectionState == Mt5ConnectionState.Connected)
        {
            try
            {
                // 获取历史K线数据 - 简化实现
                // 由于MtApi5的CopyRates API可能不同，这里暂时使用模拟数据
                // 实际使用时需要根据MtApi5的具体API进行调整
            }
            catch (Exception ex)
            {
                this.ShowMsg($"【市场数据】获取历史数据失败: {ex.Message}", LogEmuns.Warn);
            }
        }

        // 如果没有数据，使用默认值
        if (returns.Count < 20)
        {
            // 生成模拟数据（基于历史交易记录）
            for (int i = 0; i < 100; i++)
            {
                prices.Add(1.2000 + i * 0.0001);
            }

            for (int i = 1; i < prices.Count; i++)
            {
                double logReturn = Math.Log(prices[i] / prices[i - 1]);
                returns.Add(logReturn);
            }
        }

        marketData.Prices = prices;
        marketData.Returns = returns;

        // 获取网络延迟（毫秒）
        marketData.NetworkLatency = GetNetworkLatency();

        return marketData;
    }

    /// <summary>
    /// 创建账户状态对象用于AdaptiveHedgeOptimizer
    /// </summary>
    private AdaptiveHedgeOptimizer.AccountStatus CreateAccountStatus(MtApi5Client mtClient)
    {
        var accountStatus = new AdaptiveHedgeOptimizer.AccountStatus
        {
            LastTradeTime = DateTime.Now
        };

        if (mtClient != null && mtClient.ConnectionState == Mt5ConnectionState.Connected)
        {
            try
            {
                // 获取账户信息
                try
                {
                    double equity = mtClient.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_EQUITY);
                    double freeMargin = mtClient.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_MARGIN_FREE);
                    double marginLevel = mtClient.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_MARGIN_LEVEL);

                    accountStatus.Equity = equity > 0 ? equity : 10000;
                    accountStatus.FreeMargin = freeMargin > 0 ? freeMargin : 10000;
                    accountStatus.MarginLevel = marginLevel > 0 ? marginLevel : 1000;
                }
                catch
                {
                    // 使用默认值
                    accountStatus.Equity = 10000;
                    accountStatus.FreeMargin = 10000;
                    accountStatus.MarginLevel = 1000;
                }

                // 计算每手保证金（简化计算）
                double symbolPrice = mtClient.SymbolInfoDouble(trades.FirstOrDefault()?.Symbol ?? "EURUSD", ENUM_SYMBOL_INFO_DOUBLE.SYMBOL_BID);
                double contractSize = 100000; // 标准合约大小
                accountStatus.MarginPerLot = contractSize * symbolPrice / currentLeverageRatio;
            }
            catch (Exception ex)
            {
                this.ShowMsg($"【账户状态】获取账户信息失败: {ex.Message}", LogEmuns.Warn);

                // 使用默认值
                accountStatus.Equity = 10000;
                accountStatus.FreeMargin = 10000;
                accountStatus.MarginLevel = 1000;
                accountStatus.MarginPerLot = 1000;
            }
        }
        else
        {
            // 连接断开时使用默认值
            accountStatus.Equity = 10000;
            accountStatus.FreeMargin = 10000;
            accountStatus.MarginLevel = 1000;
            accountStatus.MarginPerLot = 1000;
        }

        // 统计连续亏损次数
        var recentTrades = trades.TakeLast(10).ToList();
        int consecutiveLosses = 0;
        for (int i = recentTrades.Count - 1; i >= 0; i--)
        {
            if (recentTrades[i].Profit < 0)
            {
                consecutiveLosses++;
            }
            else
            {
                break;
            }
        }
        accountStatus.ConsecutiveLosses = consecutiveLosses;

        return accountStatus;
    }

    /// <summary>
    /// 获取网络延迟（毫秒）
    /// </summary>
    private double GetNetworkLatency()
    {
        // 简化实现，实际应ping MT5服务器
        if (MtClientMain != null && MtClientMain.ConnectionState == Mt5ConnectionState.Connected)
        {
            try
            {
                var startTime = DateTime.Now;
                // 简单的ping测试，获取账户余额
                double balance = MtClientMain.AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE.ACCOUNT_BALANCE);
                var latency = (DateTime.Now - startTime).TotalMilliseconds;
                return latency;
            }
            catch
            {
                return 100; // 默认100ms
            }
        }
        return 100; // 默认100ms
    }

    /// <summary>
    /// 交易模式下拉框选择更改事件
    /// </summary>
    private void cmbTradingMode_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cmbTradingMode.SelectedIndex < 0 || tradingModeController == null)
            return;

        // 更新模式描述
        var selectedMode = (TradingModeController.TradingMode)cmbTradingMode.SelectedIndex;

        switch (selectedMode)
        {
            case TradingModeController.TradingMode.Manual:
                lblModeDescription.Text = "手动模式 - 使用固定参数交易";
                lblModeDescription.ForeColor = Color.Black;
                break;
            case TradingModeController.TradingMode.Basic:
                lblModeDescription.Text = "基础优化 - 启用凯利公式优化";
                lblModeDescription.ForeColor = Color.Blue;
                break;
            case TradingModeController.TradingMode.Advanced:
                lblModeDescription.Text = "高级优化 - 凯利公式 + GARCH波动率 + VaR风控";
                lblModeDescription.ForeColor = Color.DarkGreen;
                break;
            case TradingModeController.TradingMode.Full:
                lblModeDescription.Text = "完全优化 - 所有优化方法启用";
                lblModeDescription.ForeColor = Color.DarkOrange;
                break;
        }
    }

    /// <summary>
    /// 应用交易模式按钮点击事件
    /// </summary>
    private void btnApplyMode_Click(object sender, EventArgs e)
    {
        if (cmbTradingMode.SelectedIndex < 0 || tradingModeController == null)
        {
            MessageBox.Show("请先选择交易模式", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        var selectedMode = (TradingModeController.TradingMode)cmbTradingMode.SelectedIndex;
        tradingModeController.CurrentMode = selectedMode;

        // 记录模式变更
        this.ShowMsg($"【模式切换】已切换到{tradingModeController.GetModeDescription()}", LogEmuns.Success);

        // 显示当前启用的优化功能
        string enabledFeatures = "已启用功能: ";
        if (tradingModeController.IsKellyFormulaEnabled) enabledFeatures += "凯利公式 ";
        if (tradingModeController.IsGARCHEnabled) enabledFeatures += "GARCH波动率 ";
        if (tradingModeController.IsVaREnabled) enabledFeatures += "VaR风控 ";
        if (tradingModeController.IsDynamicGapEnabled) enabledFeatures += "动态敞口 ";
        if (tradingModeController.IsMarketRegimeEnabled) enabledFeatures += "市场状态检测 ";

        if (enabledFeatures == "已启用功能: ")
            enabledFeatures = "已启用功能: 无（手动模式）";

        this.ShowMsg(enabledFeatures, LogEmuns.Info);

        MessageBox.Show($"交易模式已切换到: {tradingModeController.GetModeDescription()}\n\n{enabledFeatures}",
                       "模式切换成功",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Information);
    }

    /// <summary>
    /// 仓位算法选择更改事件
    /// </summary>
    private void cmbPositionMode_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cmbPositionMode.SelectedIndex < 0)
            return;

        switch (cmbPositionMode.SelectedIndex)
        {
            case 0: // 固定增量模式
                positionMode = PositionCalculationMode.FixedIncrement;
                enableKellyOptimization = false;
                lblModeDescription.Text = "固定增量模式 - 使用固定手数增量计算仓位";
                this.ShowMsg("【仓位算法】已切换到固定增量模式", LogEmuns.Info);
                break;

            case 1: // Kelly优化模式
                positionMode = PositionCalculationMode.KellyOptimized;
                enableKellyOptimization = true;
                lblModeDescription.Text = $"Kelly优化模式 - 使用Kelly公式计算最优仓位 (安全系数:{kellySafetyFactor:F2})";
                this.ShowMsg($"【仓位算法】已切换到Kelly优化模式，安全系数:{kellySafetyFactor:F2}", LogEmuns.Success);
                break;
        }
    }

    /// <summary>
    /// 初始化交易模式UI
    /// </summary>
    private void InitializeTradingModeUI()
    {
        if (tradingModeController != null)
        {
            // 设置初始选中项
            cmbTradingMode.SelectedIndex = (int)tradingModeController.CurrentMode;

            // 触发选择更改事件以更新描述
            cmbTradingMode_SelectedIndexChanged(null, null);
        }

        // 初始化仓位算法下拉框
        if (cmbPositionMode != null)
        {
            // 根据当前配置设置默认选项
            cmbPositionMode.SelectedIndex = enableKellyOptimization ? 1 : 0;

            this.ShowMsg($"【仓位算法初始化】当前模式: {(enableKellyOptimization ? "Kelly优化" : "固定增量")}, " +
                        $"Kelly安全系数: {kellySafetyFactor:F2}", LogEmuns.Info);
        }
    }

    /// <summary>
    /// 账号切换事件处理
    /// </summary>
    private void rdoAccount_CheckedChanged(object sender, EventArgs e)
    {
        try
        {
            if (rdoMainAccount.Checked)
            {
                // 加载主账号配置
                chkEnableMainTP.Checked = mainEnableTakeProfit;
                chkEnableMainSL.Checked = mainEnableStopLoss;

                cmbMainTPMode.SelectedIndex = GetModeIndex(mainTakeProfitMode);
                cmbMainSLMode.SelectedIndex = GetModeIndex(mainStopLossMode);

                txtMainTPValue.Text = mainTakeProfitValue.ToString("F2");
                txtMainSLValue.Text = mainStopLossValue.ToString("F2");

                lblTPSLStatus.Text = "当前配置：主账号";
                lblTPSLStatus.ForeColor = Color.Blue;
            }
            else if (rdoFollowAccount.Checked)
            {
                // 加载从账号配置
                chkEnableMainTP.Checked = enableTakeProfit;
                chkEnableMainSL.Checked = enableStopLoss;

                cmbMainTPMode.SelectedIndex = GetModeIndex(takeProfitMode);
                cmbMainSLMode.SelectedIndex = GetModeIndex(stopLossMode);

                txtMainTPValue.Text = takeProfitValue.ToString("F2");
                txtMainSLValue.Text = stopLossValue.ToString("F2");

                lblTPSLStatus.Text = "当前配置：从账号";
                lblTPSLStatus.ForeColor = Color.Green;
            }

            // 更新单位标签
            UpdateUnitLabels();
        }
        catch (Exception ex)
        {
            ShowMsg($"切换账号配置失败: {ex.Message}", LogEmuns.Error, ex);
        }
    }

    /// <summary>
    /// 止盈模式下拉框选择变化
    /// </summary>
    private void cmbTPMode_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateUnitLabels();
    }

    /// <summary>
    /// 止损模式下拉框选择变化
    /// </summary>
    private void cmbSLMode_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateUnitLabels();
    }

    /// <summary>
    /// 更新单位标签
    /// </summary>
    private void UpdateUnitLabels()
    {
        if (lblTPUnit != null)
            lblTPUnit.Text = GetUnitText(cmbMainTPMode.SelectedIndex);

        if (lblSLUnit != null)
            lblSLUnit.Text = GetUnitText(cmbMainSLMode.SelectedIndex);
    }

    /// <summary>
    /// 获取单位文本
    /// </summary>
    private string GetUnitText(int modeIndex)
    {
        return modeIndex switch
        {
            0 => "倍",      // ATR
            1 => "%",       // Percentage
            2 => "点",      // Points
            3 => "美元",    // Amount
            _ => ""
        };
    }

    /// <summary>
    /// 获取模式索引
    /// </summary>
    private int GetModeIndex(string mode)
    {
        return mode switch
        {
            "ATR" => 0,
            "Percentage" => 1,
            "Points" => 2,
            "Amount" => 3,
            _ => 0
        };
    }

    /// <summary>
    /// 获取模式字符串
    /// </summary>
    private string GetModeString(int index)
    {
        return index switch
        {
            0 => "ATR",
            1 => "Percentage",
            2 => "Points",
            3 => "Amount",
            _ => "ATR"
        };
    }

    /// <summary>
    /// 应用止盈止损设置
    /// </summary>
    private void btnApplyTPSL_Click(object sender, EventArgs e)
    {
        try
        {
            // 获取界面值
            bool enableTP = chkEnableMainTP.Checked;
            bool enableSL = chkEnableMainSL.Checked;
            string tpMode = GetModeString(cmbMainTPMode.SelectedIndex);
            string slMode = GetModeString(cmbMainSLMode.SelectedIndex);

            if (!double.TryParse(txtMainTPValue.Text, out double tpValue))
            {
                MessageBox.Show("请输入有效的止盈值", "输入错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!double.TryParse(txtMainSLValue.Text, out double slValue))
            {
                MessageBox.Show("请输入有效的止损值", "输入错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 验证金额模式的输入
            if (tpMode == "Amount" && tpValue <= 0)
            {
                MessageBox.Show("金额模式止盈值必须大于0", "输入错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (slMode == "Amount" && slValue <= 0)
            {
                MessageBox.Show("金额模式止损值必须大于0", "输入错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (rdoMainAccount.Checked)
            {
                // 保存到主账号配置
                mainEnableTakeProfit = enableTP;
                mainEnableStopLoss = enableSL;
                mainTakeProfitMode = tpMode;
                mainStopLossMode = slMode;
                mainTakeProfitValue = tpValue;
                mainStopLossValue = slValue;

                SaveMainTPSLSettings();
                ShowMsg($"主账号止盈止损设置已更新 - 止盈:{(enableTP ? $"{tpMode}/{tpValue}{GetUnitText(cmbMainTPMode.SelectedIndex)}" : "禁用")}, " +
                       $"止损:{(enableSL ? $"{slMode}/{slValue}{GetUnitText(cmbMainSLMode.SelectedIndex)}" : "禁用")}",
                       LogEmuns.Success);
            }
            else if (rdoFollowAccount.Checked)
            {
                // 保存到从账号配置
                enableTakeProfit = enableTP;
                enableStopLoss = enableSL;
                takeProfitMode = tpMode;
                stopLossMode = slMode;
                takeProfitValue = tpValue;
                stopLossValue = slValue;

                SaveFollowTPSLSettings();
                ShowMsg($"从账号止盈止损设置已更新 - 止盈:{(enableTP ? $"{tpMode}/{tpValue}{GetUnitText(cmbMainTPMode.SelectedIndex)}" : "禁用")}, " +
                       $"止损:{(enableSL ? $"{slMode}/{slValue}{GetUnitText(cmbMainSLMode.SelectedIndex)}" : "禁用")}",
                       LogEmuns.Success);
            }

            lblTPSLStatus.Text = $"已应用 - {(rdoMainAccount.Checked ? "主账号" : "从账号")}";
            lblTPSLStatus.ForeColor = Color.Green;
        }
        catch (Exception ex)
        {
            lblTPSLStatus.Text = "设置失败";
            lblTPSLStatus.ForeColor = Color.Red;
            ShowMsg($"设置止盈止损失败: {ex.Message}", LogEmuns.Error, ex);
        }
    }

    /// <summary>
    /// 保存主账号止盈止损设置到配置文件
    /// </summary>
    private void SaveMainTPSLSettings()
    {
        try
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 添加或更新配置项
            if (config.AppSettings.Settings["Main.EnableTakeProfit"] == null)
                config.AppSettings.Settings.Add("Main.EnableTakeProfit", mainEnableTakeProfit.ToString());
            else
                config.AppSettings.Settings["Main.EnableTakeProfit"].Value = mainEnableTakeProfit.ToString();

            if (config.AppSettings.Settings["Main.TakeProfitMode"] == null)
                config.AppSettings.Settings.Add("Main.TakeProfitMode", mainTakeProfitMode);
            else
                config.AppSettings.Settings["Main.TakeProfitMode"].Value = mainTakeProfitMode;

            if (config.AppSettings.Settings["Main.TakeProfitValue"] == null)
                config.AppSettings.Settings.Add("Main.TakeProfitValue", mainTakeProfitValue.ToString());
            else
                config.AppSettings.Settings["Main.TakeProfitValue"].Value = mainTakeProfitValue.ToString();

            if (config.AppSettings.Settings["Main.EnableStopLoss"] == null)
                config.AppSettings.Settings.Add("Main.EnableStopLoss", mainEnableStopLoss.ToString());
            else
                config.AppSettings.Settings["Main.EnableStopLoss"].Value = mainEnableStopLoss.ToString();

            if (config.AppSettings.Settings["Main.StopLossMode"] == null)
                config.AppSettings.Settings.Add("Main.StopLossMode", mainStopLossMode);
            else
                config.AppSettings.Settings["Main.StopLossMode"].Value = mainStopLossMode;

            if (config.AppSettings.Settings["Main.StopLossValue"] == null)
                config.AppSettings.Settings.Add("Main.StopLossValue", mainStopLossValue.ToString());
            else
                config.AppSettings.Settings["Main.StopLossValue"].Value = mainStopLossValue.ToString();

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        catch (Exception ex)
        {
            ShowMsg($"保存主账号止盈止损配置失败: {ex.Message}", LogEmuns.Error, ex);
        }
    }

    /// <summary>
    /// 保存从账号止盈止损设置到配置文件
    /// </summary>
    private void SaveFollowTPSLSettings()
    {
        try
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 添加或更新配置项
            if (config.AppSettings.Settings["EnableTakeProfit"] == null)
                config.AppSettings.Settings.Add("EnableTakeProfit", enableTakeProfit.ToString());
            else
                config.AppSettings.Settings["EnableTakeProfit"].Value = enableTakeProfit.ToString();

            if (config.AppSettings.Settings["TakeProfitMode"] == null)
                config.AppSettings.Settings.Add("TakeProfitMode", takeProfitMode);
            else
                config.AppSettings.Settings["TakeProfitMode"].Value = takeProfitMode;

            if (config.AppSettings.Settings["TakeProfitValue"] == null)
                config.AppSettings.Settings.Add("TakeProfitValue", takeProfitValue.ToString());
            else
                config.AppSettings.Settings["TakeProfitValue"].Value = takeProfitValue.ToString();

            if (config.AppSettings.Settings["EnableStopLoss"] == null)
                config.AppSettings.Settings.Add("EnableStopLoss", enableStopLoss.ToString());
            else
                config.AppSettings.Settings["EnableStopLoss"].Value = enableStopLoss.ToString();

            if (config.AppSettings.Settings["StopLossMode"] == null)
                config.AppSettings.Settings.Add("StopLossMode", stopLossMode);
            else
                config.AppSettings.Settings["StopLossMode"].Value = stopLossMode;

            if (config.AppSettings.Settings["StopLossValue"] == null)
                config.AppSettings.Settings.Add("StopLossValue", stopLossValue.ToString());
            else
                config.AppSettings.Settings["StopLossValue"].Value = stopLossValue.ToString();

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        catch (Exception ex)
        {
            ShowMsg($"保存从账号止盈止损配置失败: {ex.Message}", LogEmuns.Error, ex);
        }
    }

    /// <summary>
    /// 初始化主账号止盈止损UI
    /// </summary>
    private void InitializeMainTPSLUI()
    {
        try
        {
            // 从配置加载设置
            var appSettings = ConfigurationManager.AppSettings;

            mainEnableTakeProfit = appSettings["Main.EnableTakeProfit"]?.ToLower() == "true";
            mainTakeProfitMode = appSettings["Main.TakeProfitMode"] ?? "ATR";

            if (!double.TryParse(appSettings["Main.TakeProfitValue"], out mainTakeProfitValue))
                mainTakeProfitValue = 2.0;

            mainEnableStopLoss = appSettings["Main.EnableStopLoss"]?.ToLower() == "true";
            mainStopLossMode = appSettings["Main.StopLossMode"] ?? "ATR";

            if (!double.TryParse(appSettings["Main.StopLossValue"], out mainStopLossValue))
                mainStopLossValue = 1.0;

            // 设置默认选中主账号
            rdoMainAccount.Checked = true;

            // 触发选择事件以加载对应配置
            rdoAccount_CheckedChanged(rdoMainAccount, EventArgs.Empty);
        }
        catch (Exception ex)
        {
            ShowMsg($"初始化主账号止盈止损UI失败: {ex.Message}", LogEmuns.Error, ex);
            // 使用默认值
            chkEnableMainTP.Checked = false;
            chkEnableMainSL.Checked = false;
            cmbMainTPMode.SelectedIndex = 0;
            cmbMainSLMode.SelectedIndex = 0;
            txtMainTPValue.Text = "2.0";
            txtMainSLValue.Text = "1.0";
        }
    }

    #region Combined P&L Event Handlers

    /// <summary>
    /// 处理组合盈亏监控开关变化
    /// </summary>
    private void chkEnableCombinedPnL_CheckedChanged(object sender, EventArgs e)
    {
        try
        {
            if (chkEnableCombinedPnL.Checked)
            {
                StartCombinedPnLMonitoring();
            }
            else
            {
                StopCombinedPnLMonitoring();
            }
        }
        catch (Exception ex)
        {
            ShowMsg($"切换组合盈亏监控状态失败: {ex.Message}", LogEmuns.Error, ex);
            chkEnableCombinedPnL.Checked = false;
        }
    }

    /// <summary>
    /// 启动组合盈亏监控
    /// </summary>
    private async Task StartCombinedPnLMonitoring()
    {
        try
        {
            // 检查连接状态
            if (MtClientMain?.ConnectionState != Mt5ConnectionState.Connected ||
                MtClientFollow?.ConnectionState != Mt5ConnectionState.Connected)
            {
                ShowMsg("请先连接主账号和从账号", LogEmuns.Warn);
                chkEnableCombinedPnL.Checked = false;
                return;
            }

            // 检查服务是否初始化
            if (combinedPnLService == null)
            {
                ShowMsg("组合盈亏服务未初始化", LogEmuns.Error);
                chkEnableCombinedPnL.Checked = false;
                return;
            }

            // 配置服务参数
            var settings = combinedPnLService.GetSettings();
            settings.TargetNetProfit = double.Parse(txtTargetProfit.Text);
            settings.SafetyFactor = (double)nudSafetyFactor.Value;
            settings.CheckIntervalMs = (int)nudCheckInterval.Value;

            // 启动监控
            isMonitoringCombinedPnL = true;
            combinedMonitoringCts = new CancellationTokenSource();

            ShowMsg($"启动组合盈亏监控 - 目标:{settings.TargetNetProfit}$ 安全系数:{settings.SafetyFactor} 间隔:{settings.CheckIntervalMs}ms", LogEmuns.Info);
            UpdateCombinedStatus("监控中", Color.Green);

            // 开始监控任务
            await Task.Run(async () =>
            {
                while (!combinedMonitoringCts.Token.IsCancellationRequested)
                {
                    try
                    {
                        await MonitorCombinedPnL(combinedMonitoringCts.Token);
                        await Task.Delay(settings.CheckIntervalMs, combinedMonitoringCts.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    catch (Exception ex)
                    {
                        ShowMsg($"监控过程异常: {ex.Message}", LogEmuns.Error);
                        await Task.Delay(1000, combinedMonitoringCts.Token);
                    }
                }
            }, combinedMonitoringCts.Token);
        }
        catch (Exception ex)
        {
            ShowMsg($"启动组合盈亏监控失败: {ex.Message}", LogEmuns.Error, ex);
            StopCombinedPnLMonitoring();
        }
    }

    /// <summary>
    /// 停止组合盈亏监控
    /// </summary>
    private void StopCombinedPnLMonitoring()
    {
        try
        {
            combinedMonitoringCts?.Cancel();
            combinedMonitoringCts?.Dispose();
            combinedMonitoringCts = null;
            isMonitoringCombinedPnL = false;

            ShowMsg("停止组合盈亏监控", LogEmuns.Info);
            UpdateCombinedStatus("未启动监控", Color.DarkGray);
            UpdateNetPnLDisplay(0, Color.DarkGray);
        }
        catch (Exception ex)
        {
            ShowMsg($"停止组合盈亏监控失败: {ex.Message}", LogEmuns.Error, ex);
        }
    }

    /// <summary>
    /// 执行组合盈亏监控
    /// </summary>
    private async Task MonitorCombinedPnL(CancellationToken cancellationToken)
    {
        try
        {
            // 检查服务是否初始化
            if (combinedPnLService == null)
            {
                ShowMsg("组合盈亏服务未初始化", LogEmuns.Error);
                return;
            }

            // 识别对冲对
            var hedgePairs = combinedPnLService.IdentifyHedgePairs();

            if (hedgePairs == null || hedgePairs.Count == 0)
            {
                UpdateHedgePairsList(new List<HedgePair>());
                UpdateNetPnLDisplay(0, Color.DarkGray);
                return;
            }

            // 更新界面显示
            UpdateHedgePairsList(hedgePairs.Values.ToList());

            // 监控每个对冲对
            foreach (var pairKvp in hedgePairs)
            {
                if (cancellationToken.IsCancellationRequested)
                    break;

                var pair = pairKvp.Value;
                var result = combinedPnLService.CalculateCombinedPnL(pair);

                // 更新显示
                UpdateNetPnLDisplay(result.NetPnL, result.ShouldClose ? Color.Red : Color.Green);

                if (result.ShouldClose)
                {
                    ShowMsg($"对冲对达到平仓条件 - 净盈亏:{result.NetPnL:F2}$ 目标:{result.TargetAmount:F2}$", LogEmuns.Success);

                    // 执行原子平仓
                    bool closeSuccess = await combinedPnLService.ExecuteAtomicClose(pair);

                    if (closeSuccess)
                    {
                        ShowMsg($"对冲对平仓成功 - 主:{pair.MainTicket} 从:{pair.FollowTicket}", LogEmuns.Success);
                    }
                    else
                    {
                        ShowMsg($"对冲对平仓失败 - 主:{pair.MainTicket} 从:{pair.FollowTicket}", LogEmuns.Error);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ShowMsg($"监控组合盈亏异常: {ex.Message}", LogEmuns.Error);
        }
    }

    /// <summary>
    /// 手动平仓按钮点击事件
    /// </summary>
    private void btnManualClose_Click(object sender, EventArgs e)
    {
        try
        {
            if (lvHedgePairs.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择要平仓的对冲对", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show("确认要手动平仓选中的对冲对吗？", "确认平仓",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;

            // 获取选中的对冲对信息
            var item = lvHedgePairs.SelectedItems[0];
            ulong mainTicket = ulong.Parse(item.SubItems[0].Text);
            ulong followTicket = ulong.Parse(item.SubItems[1].Text);

            // 检查服务是否初始化
            if (combinedPnLService == null)
            {
                ShowMsg("组合盈亏服务未初始化", LogEmuns.Error);
                return;
            }

            // 查找对应的HedgePair
            var hedgePairs = combinedPnLService.IdentifyHedgePairs();
            var pair = hedgePairs?.Values.FirstOrDefault(p => p.MainTicket == mainTicket && p.FollowTicket == followTicket);

            if (pair != null)
            {
                Task.Run(async () =>
                {
                    bool success = await combinedPnLService.ExecuteAtomicClose(pair);
                    if (success)
                    {
                        ShowMsg($"手动平仓成功 - 主:{pair.MainTicket} 从:{pair.FollowTicket}", LogEmuns.Success);
                    }
                    else
                    {
                        ShowMsg($"手动平仓失败 - 主:{pair.MainTicket} 从:{pair.FollowTicket}", LogEmuns.Error);
                    }
                });
            }
        }
        catch (Exception ex)
        {
            ShowMsg($"手动平仓失败: {ex.Message}", LogEmuns.Error, ex);
        }
    }

    /// <summary>
    /// 更新对冲对列表显示
    /// </summary>
    private void UpdateHedgePairsList(List<HedgePair> pairs)
    {
        RunOnUiThread(() =>
        {
            lvHedgePairs.Items.Clear();

            foreach (var pair in pairs)
            {
                // 获取当前盈亏
                double mainPnL = combinedPnLService?.GetPositionPnL(MtClientMain, pair.MainTicket) ?? 0;
                double followPnL = combinedPnLService?.GetPositionPnL(MtClientFollow, pair.FollowTicket) ?? 0;
                double netPnL = Math.Max(mainPnL, followPnL) - Math.Abs(Math.Min(mainPnL, followPnL));

                var item = new ListViewItem(pair.MainTicket.ToString());
                item.SubItems.Add(pair.FollowTicket.ToString());
                item.SubItems.Add($"{mainPnL:F2}");
                item.SubItems.Add($"{followPnL:F2}");
                item.SubItems.Add($"{netPnL:F2}");

                lvHedgePairs.Items.Add(item);
            }
        });
    }

    /// <summary>
    /// 更新净盈亏显示
    /// </summary>
    private void UpdateNetPnLDisplay(double netPnL, Color color)
    {
        RunOnUiThread(() =>
        {
            lblNetPnLValue.Text = $"{netPnL:F2}";
            lblNetPnLValue.ForeColor = color;
        });
    }

    /// <summary>
    /// 更新监控状态显示
    /// </summary>
    private void UpdateCombinedStatus(string status, Color color)
    {
        RunOnUiThread(() =>
        {
            lblCombinedStatus.Text = status;
            lblCombinedStatus.ForeColor = color;
        });
    }

    #endregion

}
